I'm working with symfony and AngularJs 1.6.8 and Symfony 3.4. I have the next configuration:
base.html.twig
<html lang="en" data-ng-app="CeocApp" ng-controller="CeocController">
//css for the app
<link id="ng_load_plugins_before"/>
//more ccs for the app
<body>
....
<div class="row" ui-view></div>
....
<script src="{{ asset('assets/angular/angular/angular.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-sanitize/angular-sanitize.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-touch/angular-touch.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-ui-router/release/angular-ui-router.min.js') }}"
type="text/javascript"></script>
<script src="{{ asset('assets/angular/oclazyload/dist/ocLazyLoad.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js') }}"
type="text/javascript"></script>
<script src="{{ asset('assets/ceoc/angular_app/ceoc-angular-app.js') }}"></script>
</body>
</html>
ceoc-app.js
var CeocApp = angular.module('CeocApp', [
'ui.router',
"ui.bootstrap",
"oc.lazyLoad",
"ngSanitize"
]).config(['$interpolateProvider', function ($interpolateProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}]);
CeocApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/dashboard");
$stateProvider
.state('dashboard', {
url: "/dashboard",
templateUrl: "../templates/dashboard.html",
controller: "DashboardController as dashboard",
resolve: {
deps: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'CeocApp',
insertBefore: '#ng_load_plugins_before',
files: [
'../assets/ceoc/angular_app/controllers/dashboard-controller.js'
]
});
}]
}
})
}]);
dashboard-controller.js is a controller that works but there are the problems:
Problem 1:$http.get(Rountin.generate('route_name')) doesn't work.
When I run the app the controller is loaded and all before that $http.get() request works but the code after that doesn't()
angular.module('CeocApp').controller('DashboardController', ['$scope', '$rootScope', function ($scope, $rootScope, $http) {
$rootScope.pageTitle = 'Dashboard';
$scope.total = 2500;
alert('this line will be reached');
$http.get(Routing.generate('ceoc.dashboard')).then(function (data) {
$scope.total = 10000
}, function (data) {
});
alert('this line will never be reached');
}]);
Problem 2: $.get doesn't let me change the $scope value.
When I change $http.get() for $.get() it works and the ajax request is made but the $scope.total value is not modified.
angular.module('CeocApp').controller('DashboardController', ['$scope', '$rootScope', function ($scope, $rootScope, $http) {
$rootScope.pageTitle = 'Dashboard';
$scope.total = 2500;
$.get(Routing.generate('ceoc.dashboard')).success(function (data) {
alert('request successfull');
$scope.total = 200; //this value won't be setted
}).then(function () {
$scope.total = 6000;
});
$scope.total = '879';//this value will be setted
}]);
The server response
{"retrasadas":5,"total":10,"en_tiempo":5}
My question is how can I set properly a $scope.anyvar value after a successfull ajax request? (with $ or $http)
Am I missing something?
Thanks in advance
Using Coec's handleAjax function and it's callback parameter:
Ceoc.handleAjax(Routing.generate('ceoc.dashboard'), "GET", function (data) {
$scope.total = data.total;
$scope.$apply();
});
Related
I am trying to use a resolve to front-load data from Rates Service in my Controller (rates controller) and get a blank screen. The api works but for some reason when I go step by step, in the execution, it skips over the $http.get method within the service :-/. Does anyone have any suggestions on how to fix this? Cheers!
rates.contoller.js
(function () {
'use strict';
angular.module('print.module').controller('ratesCtrl', ['ratesTest123', function (ratesTest123) {
console.log(ratesTest123);
}]
)})();
rates.service.js
(function () {
'use strict';
angular.module('print.module').service('ratesService', ['$http', function ($http) {
vm = this;
function getRatesDataService() {
console.log("test");
return this.$http.get("api/Rates/GetRates");
}
//}
}]
)
})();
print.module.js
(function () {
"use strict";
var module = angular.module('print.module', [
'ui.router',
]);
module.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/print');
$stateProvider
.state('print', {
url: '/print',
templateUrl: "Public/scripts/sharedViews/printNavbar.html"
})
.state('print.rates', {
url: "/rates",
controller: 'ratesCtrl',
templateUrl: "Public/scripts/rates/rates.view.html",
controllerAs: 'vm',
resolve: {
ratesTest123: ['ratesService', '$q', function (ratesService, $q) {
var deferred = $q.defer();
ratesService.getRatesDataService().then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}]
}
})
$locationProvider.html5Mode(true);
});
}());
view (scripts tags only for reference)
<body ng-app="print.module">
<div ui-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"></script>
<script type="text/javascript" src="~/public/scripts/print.module.js"></script>
<script type="text/javascript" src="~/public/scripts/books/books.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/terms/terms.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/rates/rates.service.js"></script>
<script type="text/javascript" src="~/public/scripts/rates/rates.controller.js"></script>
<script type="text/javascript" src="~/public/scripts/services/modals.service.js"></script>
</body>
Assign the getRatesDataService function to your service
(function () {
'use strict';
angular.module('print.module').service('ratesService', ['$http', function ($http) {
this.getRatesDataService = function () {
console.log("test");
return $http.get("api/Rates/GetRates");
}
//}
}]
)
} )();
since it returns a promise, you can simply do the following
resolve: {
ratesTest123: ['ratesService', function (ratesService) {
return ratesService.getRatesDataService()
}]
}
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/cart.php',
controller: 'ctrl',
resolve: {
categories: function(cartService){
console.log('inside resolve categories')
return cartService.getCategories();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrl', function (categories, $scope) {
$scope.items = categories;
});
myApp.service("cartService", function ($http, $q) {
this.getCategories = function () {
var deferred = $q.defer();
$http.get('js/categories.js')
.then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
});
myApp.run(['$rootScope',function($rootScope){
$rootScope.stateIsLoading = false;
$rootScope.$on('$routeChangeStart', function(e, current, pre) {
$rootScope.stateIsLoading = true;
var fullRoute = current.$$route.originalPath;
if(fullRoute == '/')
{
console.log('load categoreis and products')
}
});
$rootScope.$on('$routeChangeSuccess', function() {
$rootScope.stateIsLoading = false;
console.log('route changed');
});
$rootScope.$on('$routeChangeError', function() {
//catch error
});
}]);
I have placed the ng-app and ng-controller directives at the top of the HTML
<html lang="en" ng-app="MyApp" ng-controller="ctrl">
But when I run the HTML I get the following error
Error: [$injector:unpr] Unknown provider: categoriesProvider <-
categories <- ctrl
How can I fix this ?
Edit: If I remove ng-controller="ctrl" from the HTML, then no errors
You got that error just because, you are using the same controller for both index.php and 'partials/cart.php'
Create a separate controller for 'partials/cart.php' to resolve this
problem
Code Snippet:
// Code goes here
var app = angular.module('app', ['ngRoute']);
app.controller('indexCtrl', function($scope) {
$scope.title = 'Header';
});
app.config(function($routeProvider) {
$routeProvider.when('/', {
template: "<ul><li ng-repeat='item in items'>{{item}}</li></ul>",
controller: 'categoryCtrl',
resolve: {
categories: function(cartService){
return cartService.getCategories();
}
}
});
});
app.controller('categoryCtrl', function (categories, $scope) {
$scope.items = categories;
});
app.service("cartService", function() {
this.getCategories = function() {
return ['A', 'B', 'C'];
};
});
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script data-require="angular-route#1.4.2" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="indexCtrl">
<h1>{{title}}</h1>
<div ng-view></div>
</body>
</html>
you have to define the categories service/factory which is injected in your controller 'ctrl'.
So i still new to angular and java script but i read it was good practical to wrap the everything into functions.
This is what i have done.
in comment is the previous version
app.js
//var app = angular.module('app',['ngRoute','ngResource','routes']);
(function(angular) {
angular.module("app.directives", []);
angular.module("app.controllers", []);
angular.module("app", ['ngRoute','ngResource','routes','app.directives','app.controllers']);
}(angular));
directives.js
/*
app.directive('footer', function () {
return {
replace: true,
templateUrl: "/template/main_footer.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
}]
}
});
*/
(function(angular) {
var footer = function () {
return {
replace: true,
templateUrl: "/template/main_footer.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
}]
};
};
footer.$inject = [];
angular.module("app.directives").controller("footer", footer);
});
controller.js
/*app.controller('HeaderController',function($scope, $location) {
$scope.isActive = function (viewLocation) {
var active = (viewLocation === $location.path());
return active;
};
});*/
(function(angular) {
var HeaderController = function($scope,$location){
$scope.isActive = function(viewLocation){
var active = (viewLocation === $location.path());
return active;
};
}
HeaderController.$inject = ['$scope','$location'];
angular.module("app.controllers").controller("HeaderController", HeaderController);
})
and how should i proceed for routes.js
angular.module('routes', []).config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html'
})
.when('/second', {
templateUrl: 'pages/second.html'
})
.when('/third', {
templateUrl: 'pages/third.html'
})
.when('/123', {
templateUrl: 'pages/123.html'
})
.otherwise({
redirectTo: '/'
});
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular-resource.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.4/angular-route.js"></script>
<script type="text/javascript" src="js/routes.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<script type="text/javascript" src="js/directives.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
But it does not work. And i find it hard to find what went wrong because i don't get a error with the development tools on google chrome
Update
Now i do call the function at the end.
But i still can't see the footer. I also added the footer.html just in case there would something i forgot there.
directives.js
(function(angular) {
var footer = function () {
return {
replace: true,
templateUrl: "/template/main_footer.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
}]
};
};
footer.$inject = [];
angular.module("app.directives").controller("footer", footer);
}(angular));
home.html
<div>
<div>
<h3>This is the homepage</h3>
</div>
<div footer></div>
</div>
In the 'directives.js' and 'controller.js' files, you forgot (angular) at the end, like in 'app.js'.
If you write a function like this:
function f() {
// do stuff...
}
it's never going to run unless you call it somewhere: f();. Now, if you want to wrap a bit of code in a function, you still want it to run immediately as if it had not been wrapped. So what you do is you call the wrapping function immediately like this:
(function f() {
// do stuff...
})();
or like this (same thing):
(function f() {
// do stuff...
}());
In that second way of writing things, the outermost parentheses are useless for the program but they help the reader see that the function will be immediately run (or "evaluated", or "called").
You can also pass anything that lives outside of the function into the function, for example angular:
(function f(angular) {
// do stuff...
}(angular));
That is because you're missing the function invocation in some of those wrappings. For example, controller.js needs to be:
(function(angular) {
var HeaderController = function($scope,$location){
$scope.isActive = function(viewLocation){
var active = (viewLocation === $location.path());
return active;
};
}
HeaderController.$inject = ['$scope','$location'];
angular.module("app.controllers").controller("HeaderController", HeaderController);
})(angular); // CALL FUNCTION
Note in the last line I added (angular); to actually call the function.
I am getting undefined for $routeParams. Here is my code:
var ngAddressBook = angular.module('ngAddressBook', ['ngRoute']);
ngAddressBook.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/list.html',
controller: 'ngAddressListController'
}).
when('/add', {
templateUrl: 'views/add.html',
controller: 'ngAddressListController'
}).
when('/details/:id', {
templateUrl: 'views/details.html',
controller: 'ngAddressDetailsController'
});
}]);
// add a controller to it
ngAddressBook.controller('ngAddressListController', ['$scope', function ($scope)
{
$scope.contacts = [
{id:1,first_name:'Jane', last_name:'Doe','Phone':'123-456789','Email':'jane#example.com'},
{id:2,first_name:'Jhon', last_name:'Doe','Phone':'123-456789','Email':'jhon#example.com'}
];
$scope.getTotalContacts = function () {
return $scope.contacts.length;
};
}]);
ngAddressBook.controller('ngAddressDetailsController', ['$scope', function ($scope,$routeParams)
{
alert($routeParams);
$scope.id = $routeParams.id;
}]);
index.html
<!doctype html>
<html ng-app="ngAddressBook">
<head>
<title>Ng Addressbook</title>
<link href="main.css" rel="stylesheet" media="screen" />
</head>
<body>
<div ng-controller="ngAddressListController">
<div id="container">
<h1>Ng Address Book</h1>
<div id="content" ng-view>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src = "angular-route.min.js"></script>
<script src="main.js"> </script>
</body>
</html>
There is a problem in controller parameter injection. You have not added $routeParams in your array injection list.
ngAddressBook.controller('ngAddressDetailsController', ['$scope','$routeParams', function ($scope,$routeParams)
{
alert($routeParams);
$scope.id = $routeParams.id;
}]);
As I found this on top on google:
apart from the missing injection - asign the object $routeParams and not the Key $routeParams.id
I found the explination here (from Sander Elias)
ngAddressBook.controller('ngAddressDetailsController', ['$scope','$routeParams', function ($scope,$routeParams)
{
$scope.id = $routeParams
alert($routeParams);
}]);
Here is the sample (from Angular official site):
angular.module('project', ['ngRoute', 'firebase']).
value('fbURL', 'https://angularjs-projects.firebaseio.com/').
factory('Projects', function(angularFireCollection, fbURL) {
return angularFireCollection(fbURL);
}).
config(function($routeProvider) {
$routeProvider.
when('/', {controller:ListCtrl, templateUrl:'list.html'}).
when('/edit/:projectId', {controller:EditCtrl, templateUrl:'detail.html'}).
when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
otherwise({redirectTo:'/'});
});
function ListCtrl($scope, Projects) {
$scope.projects = Projects;
}
function CreateCtrl($scope, $location, $timeout, Projects) {
$scope.save = function() {
Projects.add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
}
}
function EditCtrl($scope, $location, $routeParams, angularFire, fbURL) {
angularFire(fbURL + $routeParams.projectId, $scope, 'remote', {}).
then(function() {
$scope.project = angular.copy($scope.remote);
$scope.project.$id = $routeParams.projectId;
$scope.isClean = function() {
return angular.equals($scope.remote, $scope.project);
}
$scope.destroy = function() {
$scope.remote = null;
$location.path('/');
};
$scope.save = function() {
$scope.remote = angular.copy($scope.project);
$location.path('/');
};
});
}
Link: http://jsfiddle.net/TE2WR/
Firefox console shows:
[01:45:20.760] Error: [$injector:modulerr] http://errors.angularjs.org/undefined/$injector/modulerr?p0=project&p1=%5B%24injector%[...]
What's going on?
Edit:
My HTML scripts:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="http://firebase.github.io/angularFire/angularFire.js"></script>
Be sure to include ngRoute and firebase scripts so that they are available to inject as dependencies.
For example, include ngRoute like this:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js"></script>
angular.module('project', ['ngRoute']).
config(function($routeProvider) {
});
You missed angular-route.js and firebase.js and angularfire.js in jsfiddle.
This would work
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.min.js"></script>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="https://rawgithub.com/firebase/angularFire/master/angularfire.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<style>