Manasvi Manasvi - 1 year ago 72
Javascript Question

change the font color based on value that is being filtered angularjs

Though the question similar to change the font color based on value angular js But what if we are using a filter in the expression like:


<span ng-class="{'time-elapsed': timestamp | timeElapsed != 'LIVE','time-elapsed-live': timestamp | timeElapsed == 'LIVE'}">{{timestamp | timeElapsed}}</span>


.time-elapsed {
color: black;
.time-elapsed-live {
color: red;


angular.module('appName', [])
.filter('timeElapsed', ['$filter', function($filter) {
return function(input) {
if(!input) {
return "";
var currDate = new Date(;
var inputDate = new Date(input);
var diffDate = Math.abs(currDate.getTime()-inputDate.getTime());
var diffHrs = Math.floor(diffDate/(1000 * 60 * 60));

if(diffHrs < 1) {
return "LIVE";

if(diffHrs < 24) {
return diffHrs.toString() + "h";

var diffDays = Math.floor(diffHrs/24);

return diffDays.toString() + "d";

var diffMonths=Math.floor(diffDays/31);

return diffMonths.toString()+"mo";

return Math.floor(diffMonths/12).toString()+"y";

This code is giving me errors because apparently we can't put an expression like "timestamp | timeElapsed != 'LIVE'" inside ng-class. What is the correct way to do it?

Answer Source

You can try calling a function instead of calling filter directly.

Change like this

<span ng-class="getTimeElapsedClass(timestamp)">{{timestamp | timeElapsed}}</span>

inject your filter in the controller just appending the "Filter" after your filters name

Refer this link for more info on this.

in your controller define this function like this

$scope.getTimeElapsedClass = function(timestamp ){
  var filterResult = timeElapsedFilter(timestamp)
  if(filterResult !== 'Live'){
     return 'time-elapsed'
  } else{
      return 'time-elapsed-live'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download