1

I've got a global variable in my rootScope for AngularJS which has properties updated in other various places (outside of angular). For example, lets say the property 'name' is updated on it. It seems like it updates on the root scope fine and after doing an apply or firing a controller function on any child function the view eventually updates, but this is a problem.

How can I get the controllers to update the templates to reflect the rootScope changes immediately?

How can I observe any changes whatsoever on this object, and invoke apply?

Vaughan Hilts
  • 2,839
  • 1
  • 20
  • 39

2 Answers2

1

Create a watch for it on rootscope ($rootScope.$watch('varName', function (newValue) {}[,true])). The varName parameter accepts expressions with '.' for sub-objects and '[]' for array indexes. The third parameter indicates listening fire changes "inside" the object.

Maarten Winkels
  • 2,407
  • 16
  • 15
1

You can create a $watch as so:

// Assuming that $rootScope.name exists
$rootScope.$watch('name', function(newValue, oldValue)
{
    // You have access to both the newValue
    // and the oldValue
});

To $watch for objects, taking this from Angular's Site, a third boolean character is needed

objectEquality (optional) boolean: Compare object for equality rather than for reference.

// Assuming that $rootScope.obj exists
$rootScope.$watch('obj', function(newValue, oldValue)
{
    // You have access to both the newValue
    // and the oldValue
}, true);

But know that it is not a good idea to use the $rootScope to store content. You should consider using a service or a factory for that purpose. Read more about this here.

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • Does this only work on primitives? I just tried watching my 'playerInfo' object, and not much is coming up. – Vaughan Hilts Aug 05 '14 at 23:57
  • Thanks! I can see this is going to get ugly quick, though. So I should look for alternative ways. :) The issue is I have a lot of non-angular code modifying these scopes already. – Vaughan Hilts Aug 06 '14 at 00:04
  • @VaughanHilts, I was in the same position as you were because I had the jQuery mind. After reading this article (http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background), and actually spending a while and redesigning my architecture, everything was fitting within Angular framework! I suggest to just take a few minutes and rethink your structure. – Kousha Aug 06 '14 at 00:07