最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS watch array of objects with index - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论