虽然问题类似于change the font color based on value angular js但是如果我们在表达式中使用过滤器会怎么样:
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";
}
}])
这段代码给了我错误,因为显然我们不能表达像&#34; timestamp |这样的表达式。 timeElapsed!=&#39; LIVE&#39;&#34;在ng-class里面。这样做的正确方法是什么?
答案 0 :(得分:1)
您可以尝试调用函数,而不是直接调用过滤器。
像这样改变
<span ng-class="getTimeElapsedClass(timestamp)">{{timestamp | timeElapsed}}</span>
在控制器中注入过滤器,只需附加&#34;过滤器&#34;在您的过滤器名称
之后有关详细信息,请参阅此link。
你的控制器中的像这样定义这个函数
$scope.getTimeElapsedClass = function(timestamp ){
var filterResult = timeElapsedFilter(timestamp)
if(filterResult !== 'Live'){
return 'time-elapsed'
} else{
return 'time-elapsed-live'
}
}