简体   繁体   English

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

[英]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: 虽然这个问题类似于基于值js更改字体颜色的问题,但是如果我们在表达式中使用过滤器,例如:

HTML: HTML:

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

CSS: CSS:

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

JAVASCRIPT: 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. 这段代码给了我错误,因为显然我们不能在ng-class内放置“ timestamp | timeElapsed!='LIVE'”之类的表达式。 What is the correct way to do it? 正确的方法是什么?

You can try calling a function instead of calling filter directly. 您可以尝试调用一个函数,而不是直接调用filter。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM