After some reading I noticed there are some doubts about using $watch
, considering performance. I found another solution using $observe
.
A good read on $watch
and $observe
: https://stackoverflow.com/a/14907826/2901207
javascript:
var app = angular.module('angularjs-starter', []);
app.directive('highlightOnChange', function() {
return {
link : function(scope, element, attrs) {
attrs.$observe( 'highlightOnChange', function ( val ) {
console.log("Highlighting", val);
element.effect('highlight');
});
}
};
});
app.controller('myController', function($scope, $timeout) {
$scope.val = 1;
$scope.updateVal = function() {
$scope.val = $scope.val + 1;
};
});
html:
<body ng-controller="myController">
<div highlight-on-change="{{val}}">
Total: {{ val }}
</div>
<button ng-click="updateVal()">Add to Total</button>
</body>
original source: http://plnkr.co/edit/FFBhPIRuT0NA2DZhtoAD?p=preview
from this post: https://groups.google.com/d/msg/angular/xZptsb-NYc4/YH35m39Eo2wJ
A bit more complex usage, which works perfect for me because it highlights the specific column when an update is coming.
<table class="table table-hover">
<tr>
<th ng-repeat="col in fc.tableColumns"><!--fc is a controller-->
{{col.displayName}}
</th>
</tr>
<tr ng-repeat="item in fc.items track by item.id">
<td highlight-on-change="{{value}}" ng-repeat="(key,value) in item">
@*{{key}} =*@ {{value}}
</td>
</tr>
</table>
As I said, updates the specific column, while doing this somewhere in the controller.
items[index] = item;//item from server