admin 管理员组

文章数量: 1086019

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?

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?

Share Improve this question asked May 13, 2014 at 10:18 Jelle SmeetsJelle Smeets 1584 silver badges11 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

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);

You can use $watchGroup(watchExpressions, listener).

For e.g.:

$scope.chartSeries = [{"location": {values}, "id":"serie-1", "meter":{values}, "name": "seriename", "data":[{1,2,4,5,7,4,6}]}];

$scope.$watchCollection('chartSeries ', randomFunction(var) {
//code
});

Or you can use watch for individual values in array to know which ones got changed.

本文标签: javascriptAngularJS watch array of objects with indexStack Overflow