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...
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Will this work if it is changed outside of the scope of angular, such as it would in legacy code?
Updated with more details on that.
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.
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 !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.