1

I am defining a global $rootScope variable like this:

var app = angular.module("demoApp", []);
app.run(function ($rootScope) {
    $rootScope.test = "Global"; 
});

and in my html if I access this as {{test}} it works.

But in my controller if I change the value of this variable inside my controller and change the location using $location.path(....); then this global variable value remain same.

function myCtrl($location, $rootScope) {
    $rootScope.test = "Changed to Local"; 
    $location.path("New.html");
}

Now in my New.html if I access this variable {{test}} it prints as 'Global' instead of 'Changed to Local'. But if I refresh the page, then it works fine.

Please help how to avoid this refresh issue. Can I use resolve/promise inside the ' app.run.....'? If so how to do it.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
JPN
  • 683
  • 3
  • 11
  • 24

2 Answers2

3

It's because of the way how prototypal inheritance work (explained here). It means your local scope will get a copy of test not a reference to it. Changing rootScope's value will not change the local scope's copy.

The easiest 'fix' is to wrap the rootScope property you want to be global in an object (objects are passed by reference).

$rootScope.global = { test: "Global" };

You'll then reference it in your view using {{ global.test }}. Changing $scope.global.test will also automatically change $rootScope.global.test and vice versa.

Community
  • 1
  • 1
Martin
  • 8,876
  • 2
  • 35
  • 36
  • its not working. I have object already defined but when we change the location its not getting refreshed at the first time. Second time when I click the refresh button it works – JPN Sep 10 '13 at 16:05
  • I don't think this is the inheritance problem you mention - he is getting/setting the property on $rootScope, never $scope. – Mark Sherretta Sep 10 '13 at 16:06
  • Once the controller is initialized it will get the rootScopes current value. Changes to `$rootScope.test` won't be reflected in `$scope.test` since there's no reference between them. The value is 'updated' after the `$location.path` change because a new controller is initialized with the rootscopes updated value. @JPN are you able to create a fiddle/plunk? – Martin Sep 10 '13 at 16:13
  • @Martin no I couldn't create one as the current code I have has the entire logic and I will see if I can create one... – JPN Sep 10 '13 at 18:06
0

The solution is to define the global variables into '$routeChangeSuccess'.

var app = angular.module("demoApp", []);
app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function () {
        $rootScope.test = "Global"; 
    });
});

Thanks for the details.

JPN
  • 683
  • 3
  • 11
  • 24