1

有什么方法可以通过 $scope.$watch 检测删除或添加的项目吗?

请看下面的例子:

var data = [{id: 1}, {id: 2}, {id: 3}];

$scope.$watch(function () {return data}, function (newValue, oldValue) {
    console.log(newValue, oldValue);
    // I want to detect removing or adding here:
    // var removedItem = ...?
    // var addedItem = ...?
}, true)

data.push({id: 4});
data.splice(0, 1);

谢谢

4

4 回答 4

1

这段代码对我来说很好

x = []

$rootScope.$watch((-> x), (newValue, oldValue) ->

    changed = newValue.filter((item, index) ->
        return oldValue[index] and angular.equals(item, oldValue[index]) is no
    )
    added = newValue.filter((item, index) ->
        return not oldValue[index]
    )
    removed = oldValue.filter((item, index) ->
        return not newValue[index]
    )
    console.log('x', changed, added, removed)
, yes)
于 2015-03-17T16:59:34.283 回答
0

您可以使用$watchCollection.

从文档:

[...] 集合通过标准$watch操作进行观察,并在每次调用时检查$digest()以查看是否添加、删除或移动了任何项目。

于 2015-03-17T16:40:58.050 回答
0

没有直接的方法可以实现这一点。可能你可以使用下面的结果。

//显示新值。var diff = $(newValue).not(oldValue).get();

//显示旧值。var diff = $(oldValue).not(newValue).get();

于 2015-03-17T16:21:23.197 回答
0

AngularJS 正在对这个集合进行脏检查,并且由于您这样做的速度如此之快,因此您的控制台日志甚至不会在第二次 .splice()更改之前运行。

试试这个,添加一个$timeout(function () { }并将你的.splice()代码放在那里,现在注意 console.log 的东西。

例如:

// Make sure to add the $timeout dependency
$timeout(function () {
    data.splice(0, 1);
}, 1000);

现在您可以将内容保存在您创建的那些变量中,并注意是否有任何差异。

这是一个 jsfiddle 供参考,您可以看到对象的差异。 jsFiddle 演示

于 2015-03-17T16:16:45.930 回答