In my Angular app
var mainApp = angular.module('mainApp', ['ngCookies']);
I've defined authCtrl controller:
mainApp.controller('authCtrl', ['$scope, $cookies',function ($scope, $http, $cookies) {
$scope.credentials = {};
$scope.signCheck = function () {
a = $cookies.getObject('session_credentials');
console.log(a);
};
}]);
If I'm removing $scope declaration from array (injection array?)
mainApp.controller('authCtrl', ['$cookies',function ($scope, $http, $cookies) {
$scope becomes undefined.
If I'm removing $cookies — $cookies becomes undefined.
If I keep them both — $injector unknown provider error.
What I'm doing wrong?
Just be sure that you indicate the services in a correct order in the injector array and the controller function params:
Angular docs says:
This is the preferred way to annotate application components. This is
how the examples in the documentation are written.
For example:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
// ...
}]);
Here we pass an array whose elements consist of a list of strings (the
names of the dependencies) followed by the function itself.
When using this type of annotation, take care to keep the annotation
array in sync with the parameters in the function declaration.
Perhaps this controller definition will work for you:
mainApp.controller('authCtrl', ['$scope', '$http', '$cookies', function ($scope, $http, $cookies) {
$scope.credentials = {};
$scope.signCheck = function () {
a = $cookies.getObject('session_credentials');
console.log(a);
};
}]);
Related
I'm getting started with the meanjs stack, and have reached a bit of a headscratcher that I don't have the understanding to google properly.
I have the following files:
**
(function () {
'use strict';
angular
.module('students')
.controller('StudentsListController', StudentsListController);
StudentsListController.$inject = ['StudentsService'];
function StudentsListController(StudentsService) {
var vm = this;
vm.students = StudentsService.query();
}
}());
Using this service, I am able to get an array of Student objects in the list-students controller, next:
list-students.client.controller.js
(function () {
'use strict';
angular
.module('students')
.factory('StudentsService', StudentsService);
StudentsService.$inject = ['$resource'];
function StudentsService($resource) {
return $resource('api/students/:studentId', {
studentId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
This works as intended.
What I don't understand, is why when I try to use the same service in another controller, it seems to fail to inject, leaving me with an undefined StudentsServices variable.
What gives?
students.client.controller.js
(function () {
'use strict';
// Students controller
angular
.module('students')
.controller('StudentsController', StudentsController);
StudentsController.$inject = ['$scope', '$state', 'Authentication', 'StudentsService'];
function StudentsController ($scope, $state, Authentication, student, StudentsService) {
var vm = this;
vm.authentication = Authentication;
vm.student = student;
vm.students = StudentsService.query();
...
}());
Your inject is wrong.
'$scope', '$state', 'Authentication', 'StudentsService'
But you're telling the controller to expect
$scope, $state, Authentication, student, StudentsService
I figured it out, per
AngularJS: Factory is always undefined when injected in controller
It was that my injections need to be in the same order as the params passed into the controller function.
Aha!
I am using UI-Router and trying to access my web app's current state from within a directive, using the following:
footer.directive.js
(function () {
'use strict';
angular
.module('app')
.directive('myFooter', myFooter);
myFooter.$inject = ['$cookies', 'userFactory', '$state', '$log', '$rootScope'];
function myFooter($cookies, userFactory, $state, $log, $rootScope) {
var directive = {
restrict: 'E',
templateUrl: 'app/components/footer/footer.html',
controller: FooterController,
controllerAs: 'vm',
bindToController: true
};
return directive;
function FooterController($state) {
var vm = this;
vm.currentState = $state;
}
}
})();
footer.html
<div class="footer">
<p>{{ vm.currentState.current.name }}</p>
</div>
When I run $log.log($state) it posts an object in my console that has a current object with a name attribute that is equal to the state name that I need, but when I try to reference the $state.current.name, either on my view or by logging it to the console, it displays as an empty string.
I'm a bit new to Angular, so if someone could explain to me what is going on here or at the least how to fix this so that I can display what I want properly, that would be a huge help. Thanks!
Edit: Two other questions that I looked at before posting this one are:
This one which seems to deal more with changing a class name based on state name, and this one, which doesn't quite address my problem either (and doesn't look like it could possibly be the right way to do this.)
First of all, there is a naming bug in your posted code! (amaiFooter)
The second thing is, if you log an object, it's bound by a call by reference
So the moment you log it, you log the reference. That means when you look at it, it can contain other values than when you have logged it
But when you logged the state name and it was undefined, that was the right output!
You can try to wrap it in a $timeout function with 0 delay, just to add your code to the end of the current digest cycle, that should solve your problem
You need inject the state service on the controller as follows
(function () {
'use strict';
angular
.module('app')
.directive('myFooter', myFooter);
myFooter.$inject = ['$cookies', 'userFactory', '$state', '$log', '$rootScope'];
function myFooter($cookies, userFactory, $state, $log, $rootScope) {
var directive = {
restrict: 'E',
templateUrl: 'app/components/footer/footer.html',
controller: FooterController,
controllerAs: 'vm',
bindToController: true
};
return directive;
}
FooterController.$inject = ['$state'];
function FooterController($state) {
var vm = this;
vm.currentState = $state;
}
})();
I couldn't pass the parameter from angular controller to factory. Can any one help me on this? It works without passing parameter but when I pass it it's not.
var app = angular.module('employee', ['ui.grid', 'ui.grid.saveState', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ui.grid.pinning', 'ui.bootstrap', 'ui.grid.autoResize','ui.grid.pagination']);
app.controller('EmpCtrl', ['$scope', '$http', '$interval', '$modal', '$log', 'gridService', function ($scope, $http, $interval, $modal, $log, gridService) {
$scope.LoadNextPage = gridService.LoadNextPage("5");
}]);
var gridService = function ($http, $rootScope) {
return {
LoadNextPage: function (hh) {
alert(hh);
},
gridOptions:gridOptions
};
};
app.factory('gridService', ['$http', '$rootScope', gridService]);
And this is how I use it in the view
<span id="pcNext"
class="glyphicon glyphicon-step-forward"
ng-click="LoadNextPage()">
</span>
The problem is in your controller:
$scope.LoadNextPage = gridService.LoadNextPage("5");
This means that your LoadNextPage is not a function but rather a result of the call to a function in your service. Which btw doesn't return anything but rather just displays an alert. But in your view, you're using LoadNextPage as a function call...
Change it to this so your controller's LoadNextPage will be a function that you can call from the view.
$scope.LoadNextPage = gridService.LoadNextPage;
and in your view:
<span id="pcNext"
class="glyphicon glyphicon-step-forward"
ng-click="LoadNextPage(5)">
</span>
This should work.
Note: I suspect that your gridOptions are defined somewhere outside of scope of your code that you provided in the question so that it doesn't throw and error because of the missing (likely) object. So I considered this a typo in your code and not the actual problem.
Don't want params in your view?
No problem. You can either create a wrapper function or bind it to specific parameters in your code:
// wrap
$scope.LoadNextPage = function() {
return gridService.LoadNextPage("5");
};
// bind
$scope.LoadNextPage = gridService.LoadNextPage.bind(this, 5);
Or bake the number in your service...
Issue here is gridOptions:gridOptions is not defined which throws error.
Remove ,gridOptions:gridOptions from factory.
Check snippet for working code and compare with your code.
var app = angular.module('employee', []);
app.controller('EmpCtrl', ['$scope', 'gridService', function ($scope, gridService) {
$scope.clickMe = function() {
$scope.LoadNextPage = gridService.LoadNextPage("5");
}
}]);
var gridService = function() {
return {
LoadNextPage: function (hh) {
alert(hh);
}
};
};
app.factory('gridService', ['$http', '$rootScope', gridService]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="employee" ng-controller="EmpCtrl">
<button ng-click="clickMe()">Button</button>
</div>
you not defined gridOptions function see this link:
angular.module("myApp", []).controller("myCon", function($scope, $interval, gridService){
$scope.LoadNextPage = gridService.LoadNextPage("5");
}).factory('gridService', ['$http', '$rootScope', gridService]);
function gridService($http, $rootScope){
return {
LoadNextPage: function (hh) {
alert(hh);
}
};
}
see this link
I'm new to angular and I can't figure out why this isn't working.
When I call {{$state.current.name}} in my view it works perfectly fine, but as soon as I try to pass it to my controller, the state gets "lost".
Here is my setup:
Module:
angular.module('app', ['ui.router'])
.run(function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
})
//followed by boilerplate ui router setup
View:
<home-nav-bar></home-nav-bar>
Directive:
angular.module('app')
.directive('homeNavBar', function () {
return {
restrict: 'E',
templateUrl: 'homeNavBarView.html',
controller: 'navCtrl'
};
})
})();
Controller:
angular.module('app')
.controller('navCtrl', function ($state, $scope) {
alert($state.current.name); //returns empty
});
})();
At this point I am clueless as to why I can get the state name in the view but not in my controller..
Well, ui-router docs say you can access current state's config object using the current property of $state, so there is absolutely no need to attach anything to $rootScope. I have just tested something along the lines of (simplified a bit for readability):
angular.module('myApp')
.controller('SomeCtrl', function ($scope, $state) {
console.log($state.current);
});
The result in Chrome console is:
Object {url: "/some", templateUrl: "app/some.html", controller: "SomeCtrl", name: "some"}
So as you can see all information should be available along with the name.
I'm in the process of learning Angular, and I'm trying to set up a state with a controller using ui-router. I have a main module named app.js, and then sub-modules based on different content.
The first sub-module is diary.js. Everything is working with this controller other than the controllers. The state works in the UI, etc. When I make the controller directly in diary.js (such as controller : function () { //stuff }, it works fine). But when I try to include an already defined controller for the diary state (like it's currently written), I get the following error (I couldn't post the whole error because stackoverflow won't let me have that many links):
"Error: [ng:areq]
errors.angularjs.org/1.2.23/ng/areq?p0=DiaryCtrl&p1=not%20aNaNunction%2C%20got%20undefined
at Error (native) ...
/** diary.js */
'use strict';
(function () {
angular.module('diary', ['ui.router'])
.config(['$stateProvider', function ($stateProvider) {
// States
$stateProvider.state('diary', {
url : '/diary',
templateUrl : 'diary/html/diary.html',
controller : 'DiaryCtrl'
});
}]);
}).call();
Here is the code for the DiaryCtrl.js (the defined controller).
/** DiaryCtrl.js */
'use strict';
angular.module('diary')
.controller('DiaryCtrl', [$scope, $http, function ($scope, $http) {
$http.get('api/json/diaries.html').success(function (data) {
$scope.diaries = data;
}).error(function (status) {
console.log(status);
});
}]);
I'd appreciate any help. Let me know if you need more information.
I am fairly certain it is because your injections ($scope & $http) in the DiaryCtrl are not strings:
.controller('DiaryCtrl', [$scope, $http, function ($scope, $http)
should be:
// Notice the added quotations around the scope and http injections in the array
.controller('DiaryCtrl', ['$scope', '$http', function ($scope, $http) {