根据正在过滤的angularjs的值更改字体颜色

时间:2022-06-11 19:44:26

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:

虽然问题类似于基于值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";
    }
  }])

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?

这段代码给了我错误,因为显然我们不能在ng-class中放置像“timestamp | timeElapsed!='LIVE'”这样的表达式。这样做的正确方法是什么?

1 个解决方案

#1


1  

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'
   }
}

#1


1  

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'
   }
}