AngularJs watch window variable

前端 未结 1 756
再見小時候
再見小時候 2020-12-14 20:27

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.

相关标签:
1条回答
  • 2020-12-14 21:03

    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.

    0 讨论(0)
提交回复
热议问题