0

I am using $watch for listening to myData which is an array. In a button click I am inserting a new element into the array. I need to find the position of the newly added element from the newValue array ,which is a parameter in $watch.

$scope.myData = [{
            "name": "karthik ",
            "age": 24
        },
        {
            "name": "Vijay ",
            "age": 24,
        },
        {
            "name": "Krish",
            "age": 26,
        }];


var newData = {
    "name": "viki",
    "age": 25
}
myData.splice(2, 0, newData);

In the link function I have

scope.$watchCollection(function(scope) {
    return scope.myData;
}, function(newVal, oldVal) {
    console.log(newVal);
    console.log(oldVal);
});

2 Answers2

0

YOu can use angular.equal to compare the two values , objects, arrays.

https://docs.angularjs.org/api/ng/function/angular.equals

and as according to your statement you want the new inserted element in the array. Then after inserting element in array if you are not doing any operation of array then inserted element is the last element which you can simply retrieve.

Arun Redhu
  • 1,584
  • 12
  • 16
0

According to your requirement, I need to find the position of the newly added element from the newValue array.

I created a function to get the changed array value and also the index where it is added.

Here is the function,

function difference(a1, a2) { 
  var result = { array: [], index: 0};
  for (var i = 0; i < a1.length; i++) {
    if (a2.indexOf(a1[i]) === -1) {
      result.array.push(a1[i]);
      result.index = i 
    }
  }
  return result;
}

You can call it using, difference(newVal,oldVal)

scope.$watchCollection(function(scope) {
    return scope.myData;
}, function(newVal, oldVal) {
    console.log(newVal);
    console.log(oldVal);
    var diff = difference(newVal,oldVal)
    console.log(diff)
});

Eg:

var diff = difference([1,2,3,[2,4],4],[1,2,3,4])

O/P: {array: [2,4], index: 3}
Sravan
  • 18,467
  • 3
  • 30
  • 54
  • this will be working fine. but in the case of large data such as a1.length = 10,000 or 1,00,000 then performance will be affected know.so is there any other way? – Vignesh Ramasamy Mar 17 '17 at 10:46
  • if you want to find the index of an added element, you need to obviously loop through the array. – Sravan Mar 17 '17 at 11:08