2016-09-18 81 views
0

該代碼在這裏可用:https://plnkr.co/edit/gbbsEnXxVpLsxvtKsDxw?p=preview。過濾器filter: { a : 'x' }有效,只顯示一行。帶有「或」條件的AngularJs過濾器?

問:

  1. 看來filter: { a : 'xxx' }比賽只要文本包含字符串xxxa任何文本。如果我想做精確匹配怎麼辦?
  2. 如何實現:顯示所有行如果a = 'xxx' or b = 3不能使用c
  3. 也許最好在`model.dashbardRows上使用javascript代碼?

dashboard.component.js

(function() { 
    'use strict'; 
    angular.module('testModule', []) 
    .component('dashboard', { 
     templateUrl: 'dashboard.component.html', 
     controllerAs: 'model', 
     controller: [controller] 
    }); 

    function controller() { 
     var model = this; 
     model.dashboardRows = [ 
     {a:'xxx', b:1, c:'ss'}, 
     {a:'yyy', b:2, c:'tt'}, 
     {a:'zzz', b:3, c:'uu'}]; 
    } 
})(); 

dashboard.component.html

<div> 
    Test 
    <table> 
    <tr ng-repeat="i in model.dashboardRows | filter: { a : 'x' }"> 
     <td>{{i.a}}</td> 
     <td>{{i.b}}</td> 
    </tr> 
    </table> 
</div> 

回答

3

正如@Valery使用自定義過濾器是解決這個問題的最佳解決方案建議。

Here is fork using custom filter(multiple conditions)

dashboard.component.js

.filter("optionalFilter",function(){ 
    //console.log("filter loads"); 
    return function(items, firstArgument,secondArgument){ 
    //console.log("item is ",items); // it is value upon which you have to filter 
    //console.log("firstArgument is ",firstArgument); 
    //console.log("secondArgument ",secondArgument); 
    var filtered = []; 
    angular.forEach(items, function(value, key) { 
     //console.log("val ::",value); 
     if(value.a == firstArgument || value.b == secondArgument){ 
     // console.log("val ::",value.a); 
     this.push(value); 
     } 
    }, filtered); 
    //console.log("val ::",filtered); 
    return filtered; 
    } 

dashboard.component.html

<tr ng-repeat="i in model.dashboardRows | optionalFilter:'aaa':2"> 

有用的參考資料:

1

看看在filter filter文檔,你可以傳遞一個可選的參數comparator

true:一種用於功能速記(實際,預期){返回angular.equals(實際,預期)}。這基本上是預期和實際的嚴格比較。

請注意,這是區分大小寫的(因爲字符串比較在JS中區分大小寫)。

此外,在頁面底部還有一個示例,演示如何過濾全部或只有一個屬性。如果你的過濾很複雜,或者你的源數據很大,那麼在控制器中進行過濾也可以提高可讀性和性能。

+0

我更新的問題,並添加到列表中的另一個屬性'C',我不想'C'比較時使用。 – ca9163d9

1

我認爲你應該使用自定義過濾器

module.filter('myFilter', function(){ 
    return function(input){ 
     return input.filter(yourFilterFn); 
    }; 
}); 

ng-repeat="item in items | myFilter"