Angularjs 观察数组并获取更改的对象

big*_*ter 5 angularjs

在以角度插入或删除数组的情况下,是否可以观察数组,然后获取从数组中添加或删除的对象?我不关心数组中的对象属性,只关心添加或删除的对象本身。所以我相信 $watchCollection 很适合这里,所以它不是一个深度手表。

例如,我将此数组作为双列表框的模型:

$scope.employees = [
    {
      name: "Bob",
      id: "0"
    },
    {
      name: "Carl",
      id: "1"
    },
    {
      name: "Bill",
      id: "2"
    }
  ];
Run Code Online (Sandbox Code Playgroud)

当我将其中一个移出或移到列表框上(插入/删除)时,列表框将自动更新 $scope.employees。如果我做:

$scope.$watchCollection('employees', function(){
    //somehow get changed object
    var changedObject = ...;
    $scope.changedItems.push(changedObject);
  });
Run Code Online (Sandbox Code Playgroud)

我希望能够获取添加/删除的项目,以便我可以使用它或将其保存在某个地方。

geo*_*awg 0

处理$watchCollection函数接收新值和旧值:

$scope.$watchCollection('employees', function(newValue, oldValue){
    console.log(newValue);
    console.log(oldValue);

    var addedArray = newValue.filter(x => !oldValue.find(x));
    var removedArray = oldValue.filter(x => !newValue.find(x));

    var changedObject = {added: addedArray, removed: removedArray};
    $scope.changedItems.push(changedObject);
  });
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅AngularJS $watchCollection API 参考