AngularJs监视窗口变量 [英] AngularJs watch window variable

查看:131
本文介绍了AngularJs监视窗口变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angularJs能够观看一个全局变量

我把从传统code一window.test变量,那么我需要看该变量知道它的存在。

我试过像

  $窗口。$表(测试,函数(N,O){
    //一些code这里...
}


解决方案

一些。您可以如果包括角 $窗口服务(这是安全的,因为在该文档中解释,不是访问窗口直接):

  app.controller('myCtrl',函数($范围,$窗口){...}

然后用一块手表函数作为第一个参数的 $观看 像这样:

  $范围。$手表(
    功能(){
        返回$ window.test
    },功能(N,O){
        的console.log(改变,N);
    }
);

演示小提琴

但需要注意的是, $观看不会执行,直到触发器的东西角度做了$摘要。一种可能的方式做到这一点是包装遗留code在 $范围。$适用或触发 $消化一旦遗留code已经exectuted。下面是关于这一些好的文档。

基本上每当发生变化的角外(比如这是一个常见的​​问题,当jQuery的导致的变化)有些事情要告诉角度去看看是否有改变。这是一个边角的方式保持合理的性能。

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

解决方案

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.

这篇关于AngularJs监视窗口变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆