为什么指令不监视值的变化?

Why a directive doesn't watch the value change?

本文关键字:变化 监视 指令 为什么      更新时间:2023-09-26

我有一个指令看起来像这样:

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

我将一个项目从控制器推到favoriteParcelsList,但是$watch没有运行。我怎么做错了?我确信我错过了一些小的东西,因为我有几个其他的指令有类似的结构,他们工作得很好。

看到更多的代码(最好是实时的,在一个plunker中)将是理想的,但我怀疑你想添加元素到favoriteParcelsList,并让AngularJS捡起这些变化。如果是这样,需要注意的是,默认情况下$watch跟踪对象的身份。如果你想跟踪更复杂对象的内容,你需要使用deep-watch。

你可以指示AngularJS通过向$watch方法提供第三个布尔参数来深度监视变化(注意true在最后):

        scope.$watch('favoriteParcelsList', function (favoriteParcelsList) {
            if (scope.favoriteParcelsList != undefined)
                console.log(scope.favoriteParcelsList.length)
        }, true);