15

In angularJs is possible to watch a global variable?

I set a window.test variable from legacy code, then I need to watch that variable to know if it exists.

I've tried something like

$window.$watch("test" , function(n,o){
    //some code here...
}
Tropicalista
  • 3,097
  • 12
  • 44
  • 72

1 Answers1

25

Somewhat. You can if you include the Angular $window service (which is safer, as explained in the docs, than accessing window directly):

app.controller('myCtrl', function ($scope,$window) {...}

And then use a watch function as the first parameter to your $watch like so:

$scope.$watch(
    function () {
        return $window.test 
    }, function(n,o){
        console.log("changed ",n);
    }
);

demo fiddle

But note that the $watch won't execute until something triggers Angular to do a $digest. One possible way to do that is to wrap your legacy code in a $scope.$apply or trigger a $digest once the legacy code has exectuted. Here's some good documentation on this.

Basically whenever a change happens outside of angular (for instance this is a common issue when jQuery causes the change) something has to tell Angular to go see if something changed. It's one way Angular maintains reasonable performance.

KayakDave
  • 24,636
  • 3
  • 65
  • 68
  • 2
    Will this work if it is changed outside of the scope of angular, such as it would in legacy code? – TheSharpieOne Dec 18 '13 at 20:10
  • Updated with more details on that. – KayakDave Dec 18 '13 at 20:39
  • 6
    One other thing to note is that this will only trigger if the value of $window.test itself changes - either a primitive type (number, string, date, boolean, etc) changing values, or an object reference changing. If you want it to trigger if a property of $window.test changes, you'll need to pass `true` as the 3rd param of $watch() so that angular will check the properties instead of just equality. – Daniel Schaffer Dec 19 '13 at 05:33
  • Nice call. In my case, I used a $rootScope.$watch() this way to enable/disable logging in built or production instances of Angular apps by running "window.logging_required = true/false" in the JS console. Super useful. Thanks @KayakDave ! – RoboBear Sep 14 '17 at 23:10