16

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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
StudioTime
  • 22,603
  • 38
  • 120
  • 207

2 Answers2

25

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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Side note side note: https://docs.angularjs.org/misc/faq "[..] don't create a service whose only purpose in life is to store and return bits of data" – Arigion Nov 17 '17 at 10:15
4

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
});
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
squiroid
  • 13,809
  • 6
  • 47
  • 67
  • 1
    why you are mixing up service syntax with factory, you should use `this` instead of local `var` while using service, & shouldn't return object, do look at this http://stackoverflow.com/a/28262966/2435473 – Pankaj Parkar Apr 01 '15 at 17:35
  • Personally I like your service approach +1 for it :) – Pankaj Parkar Apr 01 '15 at 19:31