0

I would like to see the change of values in the array and if a change occurs to compare the old value with the new value, if the old value is greater than the new value to add 'red' class to element.

Controller for each item? This can be inefficient at large array.

How best way to do it?

var app = angular.module('myApp',[])
app.controller('myCtrl', function($scope,DataFactory) {
  $scope.items = DataFactory.data;}));
});
app.factory('DataFactory', function($interval){
 var data = [
    { 'value' : 1 },
    { 'value' : 2 },
    { 'value' : 3 },
    { 'value' : 4 },
    { 'value' : 5 },
    { 'value' : 6 }
  ];
  var i = 0;
  $interval(function(){
   i++;
    data[3].value = i;
  },2000);

  return {
   data : data
  }
});
.block {
  width: 50px;
  height: 50px;
  background: #ccc;
  text-align: center;
  padding-top:10px;
}
.gren {
  background: green;
}
.red {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <div ng-repeat="item in items" class="block">
      {{item.value}}
    </div>
  </div>
</body>
Daniel Twork
  • 89
  • 1
  • 5

1 Answers1

0

The best thing I can see is to do a deep $watch (third parameter true) on the array and then loop threw the new and old arrays to see which changed.

$scope.$watch('items', function(newValue, oldValue) {
  var count = newValue.length > oldValue.length ? oldValue.length : newValue.length;
  for(var i = 0; i < count; i++) {
    if(newValue[i].value != oldValue[i].value) {
      // logic here
      if(newValue[i].value < oldValue[i].value) {
        // new value is less
        newValue[i].less = true;
      }
      else {
        // new value is greater
        newValue[i].less = false;
      }
    }
    else {
      // It didn't change
    }
  }
}, true);

and here's the markup:

<div ng-repeat="item in items" class="block" ng-class="{red: item.less}">
  {{item.value}}
</div>

http://plnkr.co/edit/IhQSeXDTfcjww2oLTJCk?p=preview

Zach
  • 3,157
  • 1
  • 19
  • 32