[英]$watch how to get the which value has been changed in the array?
我是angularjs
。 在這個片段中,我有一個數組,就像-
$scope.jsonData = [{
annotationType: "Full Name:"
endOffset: "17"
startOffset: "0"
type: "FullName"
value: "A"
},
{
annotationType: "Email:"
endOffset: "188"
startOffset: "133"
type: "FullName"
value: "B"
}
]
現在,我在這里使用手表。
$scope.$watch('jsonData', function(newVal, oldVal) {
console.log("Value changed==>", newVal);
}, true);
現在,我的jsonData可能會經常更新,可能會添加元素或刪除它。 因此,我將從本表中了解如何添加了哪些元素或刪除了哪些元素,或者更新了哪些元素的值? 而且,如果添加了新值,那么該值或該值的索引是什么?
提前致謝。
我不確定,但是您可以執行以下操作:
newObjects = newVal.filter(new => !oldVal.some(new => JSON.stringify(new) == JSON.stringify(old)) )
removedObjects = oldVal.filter(old => !newVal.some(new => JSON.stringify(new) == JSON.stringify(old)) )
如果annotationType
是唯一的,那么這就是在jsonData
數組中獲取添加或刪除的元素的jsonData
。
var app = angular.module('app', []) app.controller('ctrl', function($scope){ $scope.jsonData = [{ annotationType: "Full Name:", endOffset: "17", startOffset: "0", type: "FullName", value: "A" }, { annotationType: "Email:", endOffset: "188", startOffset: "133", type: "FullName", value: "B" } ] var i = 0; $scope.addInArray = function(){ i++; $scope.jsonData.push({ annotationType: "Yo:"+i, endOffset: "17", startOffset: "0", type: "Yo", value: "Yo" }) } $scope.removeFromArray = function(){ $scope.jsonData.pop() } $scope.$watch('jsonData', function(newVal, oldVal) { if(newVal.length > oldVal.length){ var values = oldVal.map(e=>e.annotationType) //an object has been added var changed = newVal.filter(function(obj){ return !(values.includes(obj.annotationType)); }); console.log("Added object is ",changed[0]) } if(newVal.length < oldVal.length){ var values = newVal.map(e=>e.annotationType) //an object has been removed var changed = oldVal.filter(function(obj){ return !(values.includes(obj.annotationType)); }); console.log("removed object is ",changed[0]) } }, true); })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <button ng-click="addInArray()">Add</button> <button ng-click="removeFromArray()">Remove</button> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.