gpt4 book ai didi

javascript - Controller 中的 $watch 不会触发将项目插入指令中的数组

转载 作者:行者123 更新时间:2023-11-30 16:25:52 26 4
gpt4 key购买 nike

我在指令和 Controller 之间有一个双向绑定(bind)变量 publish.selected_tags

我在我的 Controller 中为该变量保留了一个$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 给数组时, Controller 中的 $watch 被触发:

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

为什么会这样?如果我想推送一个元素,我怎样才能让我的 $watch 触发?

最佳答案

$watch 用于监视范围内的属性。如果你想观看一个集合,你需要使用 $watchCollection(对于浅表观看)或 $watch('publish.selected_tags', function(newVal, oldVal){}, true)(用于深度观察)。

关于javascript - Controller 中的 $watch 不会触发将项目插入指令中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34153269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com