2015-02-08 69 views
0

有關自定義過濾器的非常簡單的問題。我沒有得到的是如何將產品對象作爲items傳遞給過濾器或過濾器如何訪問它們?Angularjs過濾器基礎知識

我想它與<li ng-repeat="product in products | priceFilter:prices>有關,但明確的解釋將有助於谷歌和閱讀angularjs文檔到目前爲止沒有什麼幫助。

JS文件

var myAppModule = angular.module('myApp', []); 

myAppModule.filter('priceFilter', function() { 
    return function(items, prices) { 
    console.log(items); 
    var filtered = [] 
    // Are all the brands active? 
    var allInActive = true; 
    for(var price in prices){ 
     if(prices[price].active){ 
     allInActive = false; 
     break; 
     } 
    } 
    if(allInActive){ 
     return items; 
    } 

    angular.forEach(items, function(item) { 

     if(item.price_desc != null){ 

     if(prices[item.price_desc].active){ 
      filtered.push(item); 
     }   
     } 
    }); 

    return filtered; 
    }; 
}); 

function ProductsController($scope, $filter) { 

    $scope.products = productsData; 
} 

HTML

<li ng-repeat="product in products | priceFilter:prices" ></li> 

回答

0

可以以類似的方式認爲棱角分明|運營商在bash命令。該|管道左側表達式的結果(在你的情況products到右側。在下面,這僅僅是一個很好的和方便的方式來調用視圖模板過濾器。

當使用|時,左邊的集合在過濾函數中發送到完整的過濾器。過濾器總是需要至少一個參數(被過濾的數組)。所以,Angular是安全做出這樣的假設,即總會有東西過濾在左側

它是稍微更容易看到底層函數調用與$filter(name)語法:

$filter('filter')(array, expression, comparator) 

上述'filter'是過濾器的名稱,然後,該第一參數array陣列申請expression即可。

因此,|只是使用$filter的便捷方式,而不必明確地通過array參數。

Link to documentation here.

+0

所以源陣列'products'保持完整,並且不會受到在products'調用'產品? – Robbo 2015-02-08 20:19:44

+0

是的,但是,您可以在右側添加另一個管道和另一個過濾器。然後將從左到右應用每個過濾器。 – 2015-02-08 20:45:06