JSFiddle - React, Tailwind, and code Playground
http://stackoverflow.com/questions/22367636/angularjs-real-time-stock-ticker-flash-highlight-green-or-red-when-value-chang
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-app="app" ng-controller="appcontrol">
<table class="table table-condensed">
<tbody>
<tr data-ng-repeat="stock in stocks track by $index" class="list" >
<td>{{ stock.code }}</td>
<td highlighter="stock.bid">{{ stock.bid }}</td>
<td highlighter="stock.ask">{{ stock.ask }}</td>
</tr>
</tbody>
</table>
<input type="button" value="poll on/off" ng-click="stop = !stop" />
<div ng-show="stop">Polling off</div>
<div ng-show="!stop">Polling on</div>
</div>
CSS
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
td {
-webkit-transition: 1s linear all;
transition: 1s linear all;
background-color: clear;
}
JavaScript
var app = angular.module("app", []);
app.controller("appcontrol", function ($scope, $timeout) {
$scope.stop = false;
$scope.stocks = [{
code: 0,
bid: 110,
ask: 100
}, {
code: 1,
bid: 100,
ask: 150
}, {
code: 2,
bid: 95,
ask: 80
},
{
code: 2,
bid: 95,
ask: 80
}, {
code: 5,
bid: 165,
ask: 160
}];
var x = false;
var poll = function () {
if ($scope.stop) return;
x= !x;
//simulate stock values rising and falling
for (var i = 0; i < $scope.stocks.length; i++) {
$scope.stocks[i].bid += Math.random()<.5 ? 0:x ? 5 : -5;
$scope.stocks[i].ask += Math.random()<.5 ? -5 : 5;
}
$timeout(poll, 2500);
};
poll();
});
app.directive('highlighter', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.highlighter, function (nv, ov) {
if (nv !== ov) {
var newclass= nv < ov ? 'highlight-red' : 'highlight-green';
// apply class
element.addClass(newclass);
// auto remove after some delay
$timeout(function () {
element.removeClass(newclass);
}, 1000);
}
});
}
};
});