Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$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

like image 913
StudioTime Avatar asked Apr 01 '15 17:04

StudioTime


People also ask

What is $rootScope in Javascript?

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.

What is the difference between rootScope and scope?

$rootscope is available globally (for all Controllers), whereas $scope is available only to the Controller that has created it.

How many $rootScope an angular application can have?

All the $scopes of an AngularJS application are children of the $rootscope. An app can have only one $rootScope.

What is rootScope digest?

$rootScope.$digest() This is used to call watcher for the entire scope. It is equivalent to $scope. $apply() with no optional function expression.


1 Answers

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

like image 96
Pankaj Parkar Avatar answered Sep 21 '22 07:09

Pankaj Parkar