簡體   English   中英

角度指令手表不起作用

[英]Angular directive watch doesn't work

我在控制器中有對象

$scope._id = '12345';
$scope.messages = {
    '12345': [
        {
        author: 'Vasya',
        message: 'Message from Vasya'
        },
        {
            author: 'Bob',
            message: 'Message from Bob'
        }]
};

HTML標記:

<div message-list="{{_id}}")></div>

我的指令:

var App = angular.module('app', [])
.directive("messageList", function() {
    return {
        link: function(scope,element,attrs) {          
            scope.$watch('messages[attrs.messageList]', function(newVal,oldVal) {
                if (newVal!==oldVal)
                {
                    console.log("newVal",newVal);
                    console.log("oldVal",oldVal);
                }
            },true);
        }
    }
});

但是當我將新元素推入數組$ scope.messages ['12345']時,手表無法正常工作。

這是一個小矮人。 在查看撥片查看更改時,打開控制台。

您需要在messages對象上使用$watch

scope.$watch('messages', function(newVal,oldVal) {
    if (newVal!==oldVal)
    {
        console.log("newVal",newVal);
        console.log("oldVal",oldVal);
    }
},true);

暫無
暫無

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

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