简体   繁体   English

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

[英]Angular js creating a custom filter that returns all items less than a dynamic number

So I have this array of items that are displayed with ng-repeat. 所以我有这一系列与ng-repeat一起显示的项目。

The items have a filter applied based on the ng-model of some input boxes. 这些项目具有基于某些输入框的ng模型应用的过滤器。

Each item has a price attribute that is a number. 每个项目的价格属性都是数字。

I want to be able to type the price in the input box and then get back all the items that are <= the price. 我希望能够在输入框中输入价格,然后取回所有<=价格的项目。

If it could be done as a custom filter that would be great but it needs to link the input box ng-model to the filter on the ng-repeat and bring back the items that are less than or equal to it. 如果可以作为自定义过滤器来做,那会很棒,但是需要将输入框ng-model链接到ng-repeat上的过滤器,并带回小于或等于它的项目。

It's kind of tricky I know but if anyone could help I would be vary grateful. 我知道这有点棘手,但是如果有人可以帮助我,我将不胜感激。

HTML 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 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 的jsfiddle

I think something like this would work. 我认为类似的方法会起作用。

          <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

            };
          };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM