0

I am using angular 1.5.6 and my application is composed of several modules, each module has his own view and controller. My question is how can I watch $rootScope on each of those controllers. I need to watch $rootScope on all controllers because I have a global variable on $rootScope.account and when user refresh the page $rootScope.account is cleared and all my application crash. I would like to watch $rootScope.account on all my modules, so when a user refresh I can handle the refresh and redirect to login page. I thought maybe of a service that I would inject on all each of my modules?

Moussa
  • 4,066
  • 7
  • 32
  • 49
  • Yes you could/should use a factory. You could also store the user account in Local Storage to avoid loosing it after a refresh. – MatthieuLemoine Sep 14 '16 at 15:29
  • Try some google chrome extension something like `ng-inpector` through which will be quite handful. Here is the URL - https://chrome.google.com/webstore/detail/ng-inspector-for-angularj/aadgmnobpdmgmigaicncghmmoeflnamj – David R Sep 14 '16 at 15:31
  • Possible duplicate of [angularjs Watching rootscope changes](http://stackoverflow.com/questions/16888166/angularjs-watching-rootscope-changes) – Bamieh Sep 14 '16 at 16:03

1 Answers1

0

You can do it in two simple ways.

First: include $rootScope into your controller:

app.controller('MyCtrl', [
    '$rootScope',
    '$scope',
    function($rootScope, $scope) {
        $rootScope.$watch('myvar', function(newValue, oldValue) {
            doSomething();
        }

        //...
    }
]);

Second. If you don't have variables with same names in the other scopes then you can avoid using $rootScope and use just $scope. This will work because every $scope is inherited from $rootScope.

app.controller('MyCtrl', [
    '$scope',
    function($scope) {
        $scope.$watch('myvar', function(newValue, oldValue) {
            doSomething();
        }

        //...
    }
]);
Stalinko
  • 3,319
  • 28
  • 31
  • Hi, thanx. The first solution would fix my issue I think, but like this I have to add function($rootScope, $scope)... on every module which would make a lot of code duplication, isn't there a way to put the $rootScope.$watch in a service and simply add inject this service in all my modules? – Moussa Sep 14 '16 at 15:36
  • 1
    just put this code in `app.run(['$rootScope', function($rootScope) { ... }])` if it doesn't depend on controllers. – Stalinko Sep 14 '16 at 16:04