Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 如何检测$scope.$watch中已删除的项目?_Angularjs_Angularjs Digest - Fatal编程技术网

Angularjs 如何检测$scope.$watch中已删除的项目?

Angularjs 如何检测$scope.$watch中已删除的项目?,angularjs,angularjs-digest,Angularjs,Angularjs Digest,是否可以通过$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: // va

是否可以通过$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);

谢谢

AngularJS正在直接检查此集合,由于您的检查速度非常快,您的控制台日志在第二次
.splice()
更改之前都不会运行

尝试此操作,添加一个
$timeout(函数(){}
,并将
.splice()
代码放在那里,现在注意console.log事件

例如:

// Make sure to add the $timeout dependency
$timeout(function () {
    data.splice(0, 1);
}, 1000);
现在,您可以将内容保存在您创建的变量中,并注意是否存在任何差异

这里有一个JSFIDLE供参考,您可以看到对象之间的差异。

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

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

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

您可以使用

从文档中:

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


这个代码对我来说很好用

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)

如何获取已删除的项目?