javascript - 为什么 angularJs $watch 只运行一次

标签 javascript angularjs

watch 中的代码只运行一次。 我该如何解决?

 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 在 Controller 启动时无法在 View 中找到该元素。要使 $watch 绑定(bind)/工作,元素应该已经存在于 View 中。

我的猜测 - 您必须在 View 中使用 ng-if。而 ng-if 只有在条件为真时才创建元素。

我两次遇到这个问题,两次都删除了 ng-if

关于javascript - 为什么 angularJs $watch 只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39061019/

相关文章:

javascript - Angular js 依赖注入(inject)不起作用

javascript - AngularJS,指令

javascript - 对象中嵌套数组的 Angular ng-repeat 过滤器

javascript - 计算 AngularJS 中特定检查值出现的次数

javascript - 检索选择的数据

javascript - 指令链接函数中的 "Scope"是根作用域,而不是指令作用域

javascript - r.js:是否可以在命令行上指定多个包含/排除?

javascript - d3.json() 回调中的代码未执行

javascript - 测试颜色和宽度?

javascript - 等待 Angular 完成更新 DOM