【问题标题】:$watch in controller not firing on pushing items into array in directive控制器中的 $watch 不会在将项目推入指令中的数组时触发
【发布时间】:2016-03-13 05:14:40
【问题描述】:

我在指令和控制器之间有一个双向绑定变量publish.selected_tags

我在控制器中的该变量上保留了$watch

$scope.$watch('publish.selected_tags', function(new_val, old_val) {
    console.log(new_val); //print new value
})

我面临的问题是当我将一个项目推入selected_tags 列表时,$watch 不会被触发:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags.push('item') //watch in the controller not getting fired
    }
}

但是,当我将selected_tags 分配给一个数组时,控制器中的$watch 会被触发:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags = ['item'] //watch in the controller getting fired!
    }
}

为什么会这样?在我想推送一个元素的情况下,如何让我的$watch 触发?

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-watch


    【解决方案1】:

    $watch 用于查看范围内的属性。如果您想观看合集,您需要使用$watchCollection(用于浅层观看)或$watch('publish.selected_tags', function(newVal, oldVal){}, true)(用于深度观看)。

    【讨论】:

      【解决方案2】:

      我认为你应该使用$watchCollection() 来观察数组的变化。 $watch() 当表达式的值发生变化时触发,如果我没记错的话,不会在您正在观察的对象内的属性发生变化时触发。

      https://code.angularjs.org/1.1.4/docs/api/ng.$rootScope.Scope#$watchCollection

      【讨论】:

        【解决方案3】:

        使用 $scope.$watchCollection(...)

        参考。 https://docs.angularjs.org/api/ng/type/$rootScope.Scope

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-20
          • 1970-01-01
          • 2016-03-17
          相关资源
          最近更新 更多