2013-05-31 26 views
3

我试图使用角度滤波器在我的HTML应用条件filltering:AngularJS - 条件格式使用过滤器

angular.module('myFilter', []).filter('conditionFormat', function() { 
    return function (input) { 
     return (input 
      ? '<span style="color:#008000; font-weight:bold;">The statement is true</span>' 
      : '<span style="color:#008000; font-weight:bold;">The statement is <span style="color: #FF0000;">NOT</span> true</span>'); 
    }; 
}); 

HTML代码:

<td> 
    <span ng-bind-html="{{statement.IsTrue | conditionFormat}}"></span> 
</td> 
在JS文件

过滤器

字面上的输出是:

<span style="color:#008000; font-weight:bold;">The statement is true</span> 

有没有办法在HTML中编码返回字符串?或者完成这个的另一种方式?

在此先感谢。

回答

2

ng-switch看起来运行良好。

HTML:

<td>          
    <div ng-switch on="statement.IsTrue"> 
     <div ng-switch-when="true"><span style="color:#008000; font-weight:bold;">The statement is true</span></div> 
     <div ng-switch-when="false"><span style="color:#008000; font-weight:bold;">The statement is <span style="color: #FF0000;">NOT</span> true</span></div> 
     <div ng-switch-default><span style="color: rgb(255, 0, 0); font-weight: bold;">No answer selected</span></div> 
    </div>            
</td> 
2

我觉得directive是一种更好的方式来实现你想要的,因为你需要根据一定的参考价值生成html,过滤器的最佳使用,但是是刚刚格式输出为

下面是一个例子:

JS

angular.module('myDir', []). 
    directive('truthful', function() { 
    return function(scope, element) { 
     function updateUi() { 
     if (scope.isTrue) { //NOTE: change to whatever you have in your scope 
      element.html('<span style="color:#008000; font-weight:bold;">The statement is true</span>'); 
     } 
     else { 
      element.html('<span style="color:#008000; font-weight:bold;">The statement is <span style="color: #FF0000;">NOT</span> true</span>'); 
     } 
     } 

     scope.$watch('isTrue', updateUi); 
    }; 
    }); 

HTML

<span truthful></span> 

我还创建了一个plunk你拿一下。

4

这将是清洁做到这一点使用CSS类和ngClass

<span class="normal">The statement is </span> 
<span ng-class="{warn:statement.IsTrue}">{{statement.IsTrue}}</span> 

随着对CSS类“正常”和“警告”适当的定义。

或者,只是使用ngShow和ngHide显示HTML的一个街区,并隐藏其他。大多数情况下,在Angular中,您操作模型,视图使用条件指令呈现它;你很少需要直接操纵HTML。