是否可以在AngularJS中同时拥有orderBy和filter?

时间:2018-04-18 09:27:29

标签: javascript angularjs

在我的表中,它工作正常orderBy(降序和升序)。它看起来像这样:

<table class="table table-striped top-scroll__content">
<thead>
    <tr>
        <th ng-click="$ctrl.sorting('Name')">Name</th>
        <th ng-click="$ctrl.sorting('Type')">Occurence</th>
        </th>
    </tr>
</thead>
    <tbody>
        <tr ng-repeat="rows in $ctrl.alertsResponse | orderBy:$ctrl.sort.active:$ctrl.sort.descending track by $index">
            <td>{{rows.Name}}</td>
            <td>{{rows.Type}}</td>
        </tr>
    </tbody>
</table>

我添加了一个下拉选择器,我从中选择type,我希望该表只显示具有所选类型的行。

JS函数运行良好,它在控制台中返回所需的结果,如下所示:

updateFilter(type) {
    debugger;
    if (type === "0") return this.alertsResponse;

    return this.alertsResponse.filter(function(item) {
        return item.Type === type;
    });
}

当我想将此功能添加到表格时,我的问题就来了。我试图将文件管理器添加到与orderBy相同的位置,但可能不是正确的方法:

<tr ng-repeat="rows in $ctrl.alertsResponse | orderBy:$ctrl.sort.active:$ctrl.sort.descending track by $index | filter:$ctrl.updateFilter(Type)">

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

无需在过滤器中传递控制器功能,只需在过滤器中传递下拉选择器文本而不是下拉选择器值

ng-model of drop down should be **type**
<tr ng-repeat="rows in $ctrl.alertsResponse | orderBy:$ctrl.sort.active:$ctrl.sort.descending track by $index | filter:Type">

OR

您可以通过在过滤器中传递对象来过滤数据,如

<tr ng-repeat="rows in $ctrl.alertsResponse | orderBy:$ctrl.sort.active:$ctrl.sort.descending track by $index | filter:{Type:type}">

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.rows = [
      {Type:1, name:'Tom'},
      {Type:2, name:'Jerry'}, 
      {Type:2, name:'Dom'},
      {Type:1, name:'Apple'}
    ];
    
    $scope.type = "1";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>


<div ng-app="myApp" ng-controller="namesCtrl">

<select ng-model="type">
	<option value="1">Tom</option>
	<option value="2">Jerry</option>
</select>


<table border="1" style="margin-top:20px">
<thead>
    <tr>
        <th >Name</th>
        <th >Occurence</th>
    </tr>
</thead>
    <tbody>
        <tr ng-repeat="rows in rows | filter:{Type:type}">
            <td>{{rows.name}}</td>
            <td>{{rows.Type}}</td>
        </tr>
    </tbody>
</table>

</div>