这里的问题可能是您是
myVar从Angular世界之外进行修改的。Angular不会一直运行摘要周期/脏检查,只有当应触发摘要的应用程序中发生某些事情时,例如Angular知道的DOM事件。因此,即使
myVar发生了变化,Angular也没有理由开始新的摘要循环,因为什么也没发生(至少Angular知道)。
因此,为了触发您的手表,您需要在更改时强制Angular运行摘要
myVar。但这有点麻烦,我认为您最好创建一个全局可观察对象,如下所示:
<!doctype html><html ng-app="myApp"><head> <script src="http://pre.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://pre.angularjs.org/1.0.5/angular.min.js"></script> <script> // Outside of Angular window.myVar = {prop: "value1"}; var myVarWatch = (function() { var watches = {}; return { watch: function(callback) { var id = Math.random().toString(); watches[id] = callback; // Return a function that removes the listener return function() { watches[id] = null; delete watches[id]; } }, trigger: function() { for (var k in watches) { watches[k](window.myVar); } } } })(); setTimeout(function() { window.myVar.prop = "new value"; myVarWatch.trigger(); }, 1000); // Inside of Angular angular.module('myApp', []).controller('Ctrl', function($scope) { var unbind = myVarWatch.watch(function(newVal) { console.log("the value changed!", newVal); }); // Unbind the listener when the scope is destroyed $scope.$on('$destroy', unbind); }); </script></head><body ng-controller="Ctrl"></body></html>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)