[英]why angularJs $watch only run once
codes in the watch run only once . 手表中的代码仅运行一次。 how can i fix it ?
我该如何解决?
this.$rootScope.$watch('tabType', () => {
if (this.$rootScope["tabType"] === TabType.Sent) {
this.$scope.refreshSentList();
} else if (this.$rootScope["tabType"] === TabType.Archive) {
this.$scope.refreshArchiveList();
} else if (this.$rootScope["tabType"] === TabType.Inbox) {
this.$scope.refreshInboxList();
} else if (this.$rootScope["tabType"] === TabType.Snooz) {
this.$scope.refreshSnoozList();
} else if (this.$rootScope["tabType"] === TabType.Trash) {
this.$scope.refreshTrashList();
}
},true);
So the probable reason for this issue is that $watch
is not able to find that element in view when controller initiates. 因此,此问题的可能原因是
$watch
在控制器启动时无法在视图中找到该元素。 For $watch
to bind/work the element should be already present in the view. 为了使
$watch
绑定/工作,该元素应已存在于视图中。
My guess - You must be using ng-if
in view. 我的猜测-您必须在视图中使用
ng-if
。 And ng-if
creates element only when the condition is true. ng-if
仅在条件为true时创建元素。
I faced this issue two times and removing ng-if
worked both times. 我两次遇到此问题,两次都删除了
ng-if
。
This is an example working on ES5, i see you use ES6 if i'm not wrong. 这是在ES5上运行的示例,如果我没记错的话,我会看到您使用ES6。
however, that shouldn't affect how $watch
work 但是,这不应该影响
$watch
工作方式
$scope.$watch('tabType', function (newValue, oldValue) {
console.log(newValue);
console.log(oldValue);
});
Also with this
on the begining isn't nessesary with $watch
另外随着
this
对开始时不与所必要的$watch
Hope this help you 希望这对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.