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

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

本文关键字:动态 小于 返回 数字 过滤器 创建 js 自定义 一个 Angular      更新时间:2023-09-26

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

项目具有基于某些输入框的ng模型应用的过滤器。

每个项目都有一个价格属性,该属性是一个数字。

我希望能够在输入框中键入价格,然后取回<=价格。

如果它可以作为一个自定义过滤器来完成,那就太好了,但它需要将输入框ng模型链接到ng重复上的过滤器,并带回小于或等于它的项目。

我知道这有点棘手,但如果有人能帮忙,我会非常感激。

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

我认为这样的东西会起作用。

          <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
            };
          };