[英]Angularjs, why this watch do not react when its variable changes?
我想在變量改變其值時觸發事物。 目的是使用此變量作為標志來指示數據庫已准備好使用,然后使用$ watch來檢測何時發生這種情況並繼續使用其他內容。
簡化版本如下:
<div ng-app="watchApp" ng-controller="watchCtrl">
{{status}}
</div>
和
angular.module('watchApp', []).controller('watchCtrl',
['$scope', 'myVariables',
function($scope, myVariables) {
$scope.status = myVariables.myVar;
$scope.$watch(
function() {return myVariables.myVar;},
function(newVal, oldVal) {
$scope.status = 'changed';
}
);
setTimeout(function(){myVariables.myVar = 1;alert('ei');},1000);
}]);
angular.module('watchApp').factory('myVariables',
['$window', '$q',
function($window, $q) {
return {
myVar: 0,
}
}]);
http://jsfiddle.net/SQuVy/218/
因此,超時應在1秒后更改變量,然后手表應觸發級聯並更改顯示的消息。
但它不起作用。 為什么? 也許是因為在Timeout中我無法訪問變量? 這里的Timeout是舉例說明問題,但我的代碼中並不存在。 我怎么能這樣做?
干杯,傑勒德
兩個變化。 首先,$ watch將觸發它設置的初始時間,因此您要檢查值是否實際更改:
if (newVal !== oldVal) {
$scope.status = 'changed';
}
其次,您需要將$ timeout注入服務並使用它而不是setTimeout,或者使用$ scope。$ apply以通知Angular更改:
setTimeout(function(){$scope.$apply(function() {
myVariables.myVar = 1;alert('ei');});},1000);
這是你的工作小提琴: http : //jsfiddle.net/jeremylikness/HU7Wn/
它的$scope.$watch
not $scope.watch
,rest完全相同,沒有任何變化
碼
angular.module('watchApp', []).controller('watchCtrl',
['$scope', 'myVariables',
function($scope, myVariables) {
$scope.status = myVariables.myVar;
$scope.$watch(
function() {return myVariables.myVar;},
function(newVal, oldVal) {
$scope.status = 'changed';
});
setTimeout(function(){myVariables.myVar = 1;alert('ei');},1000);
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.