为什么angularJs的$watch只运行一次

why angularJs $watch only run once

本文关键字:一次 运行 angularJs watch 为什么      更新时间:2023-09-26

代码在手表中只运行一次。我该怎么修理它?

 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);

所以这个问题的可能原因是$watch在控制器启动时无法在视图中找到该元素。要使$watch绑定/工作,元素应该已经存在于视图中。

我猜,你一定是在使用ng-ifng-if只在条件为真时才产生元素。

我遇到过这个问题两次,删除ng-if两次都有效。

这是一个在ES5上工作的例子,如果我没记错的话,我看到你在用ES6。

然而,这不应该影响$watch的工作

$scope.$watch('tabType', function (newValue, oldValue) {
    console.log(newValue);
    console.log(oldValue);
});

开头的this也不需要$watch

希望对你有帮助