2017-03-17 302 views
1
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
<div ng-app="myApp" ng-controller="myCtrl as vm"> 
    <form class="col2"> 
    <label for="filter-online"> 
    Filter by Online 
    </label> 
    <div class="select"> 
     <select id="filter-online" ng-model="vm.online" class="form-control" ng-options="online for online in vm.onlines"> 
     <option value="">All</option> 
     </select> 
    </div> 
    </form> 

    <form class="col2"> 
    <label for="filter-productType"> 
    Filter by Product Type 
    </label> 
    <div class="select"> 
     <select id="filter-productType" ng-model="vm.productType" class="form-control" ng-options="productType for productType in vm.productTypes"> 
     <option value="">All</option> 
    </select> 
    </div> 
    </form> 

    <table style="margin-top: 30px"> 
    <tr ng-repeat="lim in vm.stockLimits | filter:{online:vm.online || undefined, productType: vm.productType || undefined}"> 
     <td>{{lim.online}}</td> 
     <td>{{lim.productType}}</td> 
    </tr> 
    </table> 
</div> 

angular.module("myApp", []) 
    .controller("myCtrl", function($scope) { 
    var vm = this; 
    vm.onlines = ["Men", "Kids", "Ladies"]; 
    vm.productTypes = ["Shirt", "Shoe", "Belt", "Top"]; 
    vm.stockLimits = [{ 
     id: 1, 
     online: "Men", 
     productType: "Shirt" 
    }, { 
     id: 2, 
     online: "Men", 
     productType: "Shoe" 
    }, { 
     id: 3, 
     online: "Kids", 
     productType: "Belt" 
    }, { 
     id: 4, 
     online: "Ladies", 
     productType: "Top" 
    }, 
    { 
     id: 5, 
     online: "Kids", 
     productType: null 
    }] 
    }) 

我想聲明自定義過濾器來過濾online和productType並從角度html模板調用自定義過濾器。上面的內聯過濾器工作正常,但我期待將內聯過濾器轉換爲自定義過濾器。其實想要從html頁面移動過濾器功能。 注意:productType可以爲null。Convert-Inline ng-重複過濾器到自定義過濾器 - angularjs

回答

1

您可以定義自定義過濾器下面的方式

angular.module("myApp").filter('productFilter', function() { 
    return function(items, filterOptions) { 
     if (!items) { 
      return [] 
     } 

     return items.filter(function(item) { 
      var isOnlinePassed = filterOptions.online ? (item.online === filterOptions.online) : true, 
       isProductTypePassed = filterOptions.productType ? (item.productType === filterOptions.productType) : true; 
      return isOnlinePassed && isProductTypePassed; 

     }) 
    } 
}) 

然後使用過濾器在你的模板,如:

<table style="margin-top: 30px"> 
    <tr ng-repeat="lim in vm.stockLimits | productFilter:{online:vm.online , productType: vm.productType}"> 
     <td>{{lim.online}}</td> 
     <td>{{lim.productType}}</td> 
    </tr> 
    </table> 
+0

謝謝你,但有一個問題,它即時通訊無法弄清楚當我將此過濾器集成到現有的角度js模塊中時。如果我有第二個參數不是空的angular.module(「myApp」,'服務'),過濾不起作用 – user2057006

+0

錯誤:[$注射器:unpr]未知提供者:productFilterFilterProvider < - productFilterFilter – user2057006

+0

瀏覽器問題我猜。現在它按預期工作。做得好。謝謝。 :) – user2057006