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:
HTML:
<span ng-class="{'time-elapsed': timestamp | timeElapsed != 'LIVE','time-elapsed-live': timestamp | timeElapsed == 'LIVE'}">{{timestamp | timeElapsed}}</span>
CSS:
.time-elapsed {
color: black;
}
.time-elapsed-live {
color: red;
}
JAVASCRIPT:
angular.module('appName', [])
.filter('timeElapsed', ['$filter', function($filter) {
return function(input) {
if(!input) {
return "";
}
var currDate = new Date(Date.now());
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);
if(diffDays<31)
return diffDays.toString() + "d";
var diffMonths=Math.floor(diffDays/31);
if(diffMonths<12)
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?
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'
}
}