0

我有一个如下所示的指令:

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 没有运行。我该怎么办?我确信我遗漏了一些小东西,因为我有几个其他具有类似结构的指令并且它们工作正常。

4

1 回答 1

2

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

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

        scope.$watch('favoriteParcelsList', function (favoriteParcelsList) {
            if (scope.favoriteParcelsList != undefined)
                console.log(scope.favoriteParcelsList.length)
        }, true);
于 2013-03-05T14:58:03.363 回答