AngularJs 观察窗口变量 [英] AngularJs watch window variable
问题描述
在 angularJs 中可以查看全局变量吗?
In angularJs is possible to watch a global variable?
我从旧代码中设置了一个 window.test 变量,然后我需要观察该变量以了解它是否存在.
I set a window.test variable from legacy code, then I need to watch that variable to know if it exists.
我尝试过类似的东西
$window.$watch("test" , function(n,o){
//some code here...
}
推荐答案
有点.如果您包含 Angular $window
服务,则可以(如文档中所述,这比直接访问 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) {...}
然后使用 watch 函数作为 $watch
<的第一个参数/a> 像这样:
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);
}
);
但请注意,$watch
不会执行,直到某些东西触发 Angular 执行 $digest.一种可能的方法是将遗留代码包装在 $scope.$apply
中,或者在遗留代码执行后触发 $digest
.这里有一些很好的文档.
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.
基本上,每当在 angular 之外发生更改时(例如,这是 jQuery 导致更改时的常见问题),必须有一些东西告诉 Angular 去查看是否有更改.这是 Angular 保持合理性能的一种方式.
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屋!