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
Root Scope All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.
$rootscope is available globally (for all Controllers), whereas $scope is available only to the Controller that has created it.
All the $scopes of an AngularJS application are children of the $rootscope. An app can have only one $rootScope.
$rootScope.$digest() This is used to call watcher for the entire scope. It is equivalent to $scope. $apply() with no optional function expression.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With