简体   繁体   中英

$rootScope is not defined

I'm trying to use a cookie value in multiple places and within multiple controllers but I get error saying $rootScope is not defined

Here's the code:

capApp.controller('cookieCtrl', ['$scope','$cookies', function($scope, $rootScope, $cookies) {
  // set variable for nav
  $rootScope.cookieSet = $cookies.user_id;
}]);

capApp.controller('mainController', function($scope, $location) {  
  $scope.user_id = $rootScope.cookieSet; // set global var
});

Is there a better way to do this? Basically I want the cookie value available site wide

You missed to add $rootScope dependency in both controllers

Code

capApp.controller('cookieCtrl', ['$scope','$rootScope', '$cookies', 
  function($scope, $rootScope, $cookies) {
  // set variable for nav
  $rootScope.cookieSet = $cookies.user_id;
}]);

capApp.controller('mainController', ['$scope', '$location', '$rootScope', 
  function($scope, $location, $rootScope) {  
  $scope.user_id = $rootScope.cookieSet; // set global var
});

Ensure array annotation of dependency injection to ensure it won't break the code while doing JavaScript minification.

Side Note:- Don't use $rootScope for sharing application common function / data, do use service/factory for the same

You didn't inject $rootScope in mainController

capApp.controller('mainController', function($scope,$rootScope, $location) {  
  $scope.user_id = $rootScope.cookieSet; // set global var
});

Update:

First create a service that acts like a bridge between controllers:

1) addCookie used to add cookieset.

2) getCookie used to get cookieset.

capApp.factory('user', function() {
  var cookieSet;

  var addCookie = function(val) {
      cookieSet=val;
  }

  var getCookie = function(){
      return cookieSet;
  }

  return {
    addCookie : addCookie,
    getCookie : getCookie 
  };

});

capApp.controller('cookieCtrl', ['$scope', 'user', '$cookies', function($scope, user, $cookies) {
  // set variable for nav
  user.addCookie($cookies.user_id);
}]);

capApp.controller('mainController', function($scope, $location,user) {  
  $scope.user_id =user.getCookie(); // set global var
});

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