Angular 指令监视不起作用

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'].

时 watch 不工作

这是一个 plunkr. 在查看 plunker 的同时打开控制台以查看更改。

您需要 messages 对象上的 $watch

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