我是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可能会经常更新,可能会添加一个元素或删除。那么,我从这个手表中如何知道添加了哪个元素,哪个元素已被删除或哪些元素值已更新?而且,如果添加了新值,那么该值的值或索引是什么?
提前致谢。
答案 0 :(得分:0)
我不确定,但你可以这样做:
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)) )
答案 1 :(得分:0)
如果annotationType
是唯一的,那么这就是获取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>
答案 2 :(得分:0)