Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS watch array of objects with index

I have a question about Angular watch within an array of objects.

I have an array $scope.chartSeries with objects as following:

[{"location": {values}, "id":"serie-1", "meter":{values}, "name": "seriename", "data":[{1,2,4,5,7,4,6}]}]

This is used to draw a linechart with highcharts.

I want to watch this array, and if a value changes I want to know the index and the value that is being changed.

I found several options for watch but none of them seem to fit my situation. Can you help me out?

like image 631
Jelle Smeets Avatar asked Feb 13 '23 00:02

Jelle Smeets


1 Answers

If you render and change your array in ng-repeat, you can use ng-change directive and pass in it a $index parameter.

For example:

<div ng-repeat="item in array">
   <input type="text" ng-model="item.location" ng-change="changeValue($index)"/>
</div>

Or you can use $watch and work with newValue, oldValue parameters

$scope.$watch('array', function (newValue, oldValue) {
   for(var i = 0; i < newValue.length; i++) {
      if(newValue[i].location != oldValue[i].location)
        var indexOfChangedItem = i;
        //bla-bla-bla
   }
}, true);
like image 59
Artyom Pranovich Avatar answered Feb 16 '23 03:02

Artyom Pranovich