簡體   English   中英

為什么指令不會觀察價值變化?

[英]Why a directive doesn't watch the value change?

我有一個看起來像這樣的指令:

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跟蹤對象的標識。 如果要跟蹤更復雜對象的內容,則需要使用深度監視。

您可以通過向$watch方法提供第三個布爾參數來指示AngularJS深入監視更改(在結尾處注意為true ):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM