如何使用输入字段过滤空字符串值的ng-repeat列表?

时间:2017-07-20 13:02:36

标签: angularjs angularjs-ng-repeat angularjs-filter

如何过滤ng-repeat以显示某个列字段为空字符串的所有项目?当我通过在字段中输入任何内容来尝试此操作时,它似乎总是给出完整列表(预期)。我只想查看ID为1的人。如何调整输入字段中某个字符对名称列的空字段进行ng重复过滤的过滤器。

FiddleJs Example

我的观点:

<div class="panel-heading">
   <h3>Filtered by {{filterValue}}</h3>
   <input ng-change="filter()" ng-model="filterValue"/>
</div>
<div class="panel-body">
   <ul class="list-unstyled">
     <li ng-repeat="p in filteredPeople">
       <h4>{{p.name}} ({{p.age}}) id: {{p.id}}</h4>
     </li>
   </ul>
</div>

控制器:

    var people = [{
        name: '',
        age: 32,
        id: 1
    }, {
        name: 'Jonny',
        age: 34,
        id: 2
    }, {
        name: 'Blake',
        age: 28,
        id: 3
    }, {
        name: 'David',
        age: 35,
        id: 4
    }];

    $scope.filter = function (value) {
     $scope.filteredPeople = $filter('filter')(people, {
        name: $scope.filterValue
     });
    }

    $scope.people = people.slice(0);

1 个答案:

答案 0 :(得分:1)

删除控制器中的$scope.filter()功能和视图中的ng-change="filter()"。您应该将var people数组更改为$scope.people。您还需要删除行$scope.people = people.slice(0);

在控制器中创建一个过滤器功能,仅在name为空时返回$scope.filterValue属性为空的人:

$scope.emptyFilter = function(person) {
    if ($scope.filterValue.length === 0) {
        if (person.name.length === 0) {
            return person;
        }
    } else {
        return person;
    }
};

接下来,使用以下内容更新您的ng-repeat

<li ng-repeat="p in people | filter:emptyFilter | filter:{name: filterValue}">