Darren Sweeney Darren Sweeney - 3 months ago 69
AngularJS Question

$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

Answer

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 data, do use service/factory for the same