簡體   English   中英

$ watch如何獲取數組中已更改的值?

[英]$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> 

當使用$ scope。$ watch時,您僅在驗證值是否已更改(如果它是原始變量)或引用是否已更改(如果監視的變量是引用變量(例如數組和對象))。

如果要監視數組中的更改,請使用$ watchCollection。 如果要監視數組元素的變化,請使用$ watch,將最后一個參數傳遞為'true'。

請注意,這都會影響應用程序的性能。 按價值衡量的手表性能最低,而按參考價值的手表則性能最高。

所有這些都可以在下圖中看到:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM