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 02 Answers
Reset to default 7If 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.