Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs watch window variable

Tags:

angularjs

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...
}
like image 759
Tropicalista Avatar asked Dec 18 '13 19:12

Tropicalista


People also ask

What is $scope in angular?

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.

What is$ window in Angular?

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.

What is $location in AngularJS?

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.

What is $document in AngularJS?

A jQuery or jqLite wrapper for the browser's window.


1 Answers

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.

like image 110
KayakDave Avatar answered Sep 22 '22 15:09

KayakDave