2013-11-20 185 views
4

如果你看看下面的代碼,我想使用文本<input>來過濾每個菜單項的多個成分 - 例如,如果用戶在<input>中輸入「牛肉,培根」,應用程序將返回所有與牛肉或培根作爲配料的菜單項目。AngularJS過濾 - 多個表達式或動態鏈接過濾器?

我目前正在嘗試使用ng-filter來做到這一點,我猜我需要爲此創建一個自定義過濾器。這是錯誤的做法?有沒有辦法動態鏈式過濾器呢?

下面是一些代碼,應該讓我的問題意識 -

我的搜索模式: - 注意:使用NG列表把字符串轉換成字符串數組

<div ng-init="searchString=[]"> 
    <input type="text" ng-model="searchString" ng-list> 
</div> 

我的重複循環: - 注意:使用自定義過濾器將每個成分加入到一個字符串中

<tr ng-repeat="item in menu | filter:{ category : 'Classics' } | filter:{ ingredients : searchString } "> 
    <td class="title">{{ item.title }}</td> 
    <td class="ingredients"> 
     {{ item.ingredients | join:', ' }} 
    </td> 
    <td class="price">{{ item.price | currency }}</td> 
</tr> 

我的數據結構

$scope.menu = [ 
    { 
     "title" : "New Yorker", 
     "price" : "4.00", 
     "ingredients" : [ 
      "Salt Beef", 
      "Pickles", 
      "Mustard" 
     ], 
     "category" : "Classics" 
    }, 
    { 
     "title" : "BLT", 
     "price" : "4.00", 
     "ingredients" : [ 
      "Bacon", 
      "Lettuce", 
      "Tomato" 
     ], 
     "category" : "Classics" 
    } 
] 

回答

1

您可以創建自定義過濾器,或使用角度濾波與謂語(函數)

{ filter_expression | filter:predicateFunction }} 
當然

,你的函數住在您的控制器的範圍內,搜索字符串可見

謂詞函數可用於編寫任意過濾器。爲數組的每個元素調用 函數。最終結果是謂詞返回true的那些元素的 數組。

http://docs.angularjs.org/api/ng.filter:filter

2

(我拿到這可能是一個死的問題,但我發現它也因此:)

因爲要篩選至少共享菜單項需要一個自定義過濾器一種成分與您的搜索列表(即非空陣列相交)。在問題filter:{ ingredients : searchString }中使用的過濾器不會以這種方式進行過濾,也不會從其official doc內置到Angular中的任何其他過濾器。

創建自定義過濾器很簡單;添加新功能containsIngredientsFromSearch$scope

// Filter functions are called separately for each item on the menu 
$scope.containsIngredientsFromSearch = function(menuItem){  
    // Check every ingredient on the search list ... 
    for(var i in $scope.searchString) { 
    var ingredient = $scope.searchString[i]; 
    // ... does it match an ingredient in menuItem.ingredients? 
    if(menuItem.ingredients.indexOf(ingredient) !== -1) { 
     // ... if so, stop searching and return true to include this menuItem 
     return true; 
    } 
    } 

    // No matching ingredient found? Return false to exclude this item. 
    return false; 
} 

過濾器添加到現有的過濾器鏈:

<tr ng-repeat="item in menu | filter:{ category : 'Classics' } | filter:containsIngredientsFromSearch">

看到它在行動on JSBin