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...
}
AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.
The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.
A jQuery or jqLite wrapper for the browser's window.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With