我有一个如下所示的指令:
directive('parcelsCarousel',function () {
return {
restrict:'E',
replace:true,
transclude:true,
templateUrl:'/partials/parcels-carousel.html',
link:function (scope, element, attrs) {
scope.$watch('favoriteParcelsList', function (favoriteParcelsList) {
if (scope.favoriteParcelsList != undefined)
console.log(scope.favoriteParcelsList.length)
});
}
}
});
我从 Controller 将一个项目推送到 favoriteParcelsList
,但 $watch 不运行。
我能以错误的方式做什么?我确信我错过了一些小事情,因为我还有几个具有类似结构的其他指令,并且它们工作得很好。
最佳答案
看到更多代码(最好是实时的,在 plunker 中)肯定是理想的选择,但我怀疑您想要将元素添加到 favoriteParcelsList
并让 AngularJS 拾取这些更改。如果是这样,需要注意的是,默认情况下 $watch
会跟踪对象的身份。如果您想跟踪更复杂对象的内容,您需要使用深度监视。
您可以通过向 $watch
方法提供第三个 bool 参数来指示 AngularJS 深度监视更改(注意末尾的 true):
scope.$watch('favoriteParcelsList', function (favoriteParcelsList) {
if (scope.favoriteParcelsList != undefined)
console.log(scope.favoriteParcelsList.length)
}, true);
关于javascript - 为什么指令不观察值的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15226722/