2013-05-31 56 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。