在AngularJS中按数字过滤数组

时间:2016-04-04 16:25:46

标签: javascript angularjs

我想知道我是否可以像AngularJS中的代码那样做。目标是通过所有ID> =搜索ID过滤数组。我可以在线搜索,还是必须在javascript中作为自定义过滤器完成?

<div style="margin-top:5px;margin-left:30px;">
    <div>
        <div>ID</div>
        <span class="glyphicon glyphicon-search"></span>&nbsp;
        <input type="text" ng-model="listFoodItems.searchid" />
    </div>
    <table class="table table-responsive">
        <thead>
            <tr>
                <th>ID</th>
                <th>Description</th>
                <th>Discount</th>
            </tr>
        </thead>
        <tfoot></tfoot>
        <tbody>
            <tr ng-repeat="row in listFoodItems.fullitemdescs | filter: EntryId >= searchid">
                <td>{{row.EntryId}}</td>
                <td>{{row.ItemDesc}}</td>
                <td>{{row.ItemDisc}}</td>
            </tr>
        </tbody>
    </table>
</div>

2 个答案:

答案 0 :(得分:2)

Best way make a custom filter like:

HTML

    <div ng-app>
    <div ng-controller="MyCtrl">
    <input type="text" ng-model="searchid" />
       <ul>
           <li ng-repeat="person in people | filter:myFilter">
               {{person.id}}
               -
               {{person.name}}
           </li>
       </ul>
    </div>
</div>

JS

function MyCtrl($scope){

    $scope.people = [
        {id: 1, name: "Mark"},
        {id: 2, name: "John"},
        {id:3, name: "Joe"}
    ];
    $scope.myFilter = function(item){
        if(item.id >= $scope.searchid){
            return item;
        }
    };
}

here its my fiddle with example: https://jsfiddle.net/javierif/mmoo3s8m/

答案 1 :(得分:0)

First, create a function

$scope.lessThan = function(prop, val){
    return function(item){
        return item[prop] < val;
    }
}

Next, in your ng-repeat

<tr ng-repeat="row in listFoodItems.fullitemdescs | filter: lessThan('EntryId', searchid)">

Original answer here: https://stackoverflow.com/a/24081564/5141584