Angular js创建自定义过滤器,返回小于动态数字的所有项目

时间:2014-11-07 20:45:27

标签: javascript angularjs angular-filters

所以我有这个用ng-repeat显示的项目数组。

这些项目根据某些输入框的ng-model应用了过滤器。

每个项目的price属性都是一个数字。

我希望能够在输入框中输入价格,然后取回所有< =价格的商品。

如果它可以作为自定义过滤器完成,但它需要将输入框ng-model链接到ng-repeat上的过滤器并带回小于或等于它的项目。

我知道这有点棘手,但如果有人能提供帮助,我会感激不尽。

2 个答案:

答案 0 :(得分:1)

<强> HTML

<div ng-app="app" ng-controller="ctrl">
    Max price: <input type="text" ng-model="maxPrice">
    <ul ng-repeat="e in items | cheaperThan:maxPrice">
        <li>Item name: {{e.name}}, price: {{e.price}}$</li>
    </ul>
</div>

<强>的JavaScript

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

app.controller('ctrl', function($scope){
    $scope.maxPrice = 100;
    $scope.items = [
        {name: 'Item 1', price: 123},
        {name: 'Item 2', price: 110},
        {name: 'Item 3', price: 90},
        {name: 'Item 4', price: 80}
    ];
});

app.filter('cheaperThan', function(){
    return function(ar, maxPrice){
        console.log(ar);
        return ar.filter(function(e){
            return e.price <= maxPrice;
        });
    };
});

JSFiddle

答案 1 :(得分:0)

我认为这样的事情会起作用。

          <input type="text" ng-model="somevalue"/>
          <div ng-repeat="item in myitems | filter:myfilter(item)"></div>


          $scope.somevalue;
          $scope.myfilter = function(item) {
            return function(theItem) {
              // Return true or false base on the item and $scope.somevalue

            };
          };