简体   繁体   中英

Angular: strange behavior with ngCookies

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);
    };
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM