ng-repeat过滤器"显示所有"如果未选择过滤器,则为项

时间:2015-01-27 06:35:51

标签: angularjs

我有一个ng-repeat过滤器,它使用<select>菜单来过滤一堆国家。

例如:

<div class="col-md-3 col-sm-6" ng-repeat="item in listings | filter: { location: locationFilter }">

我怎样才能这样做,如果没有选择任何内容,它会自动显示所有国家/地区?并且只有在选择特定国家/地区后才开始过滤?

我确定这可能是一个简单的问题,但我对此很新,并且无法找到如何做到这一点。

谢谢!

5 个答案:

答案 0 :(得分:28)

如果过滤器表达式返回undefined,则过滤器将不适用。所以,您可以执行以下操作:

<div ng-repeat="item in listings | filter:(!!locationFilter || undefined) && {location: locationFilter}">
   {{item}}
</div>

!!locationFilter处理'',falsy和undefined

plunker

答案 1 :(得分:4)

我建议你在ng-repeat | filter

中保留一份简单的声明性陈述

然后在<select>标记中为All添加一个字段:

<select ng-model="search.filter">
    <option value="{{undefined}}">All</option>
    <option ng-repeat="field in locations" value="field">field</option>
</select>

答案 2 :(得分:2)

我试过这个并且有效

 <select ng-options="model.FeatureVersion as model.FeatureVersion for model in PostDataResponse" ng-model="featureVersion">
             <option value="">All</option>
            </select>
<table>
    <tr ng-repeat="model in PostDataResponse  | filter:{FeatureVersion: !!featureVersion?featureVersion: undefined  }">
        <td>{{model.ClientId}}</td>
    </tr>
</table>

答案 3 :(得分:0)

这是我如何实现这个http://jsfiddle.net/L5wcgdhy/:-

的小提琴

HTML: -

<div ng-controller="MyCtrl">
 <select ng-model="filter.categoryId">
        <option value="!!"></option>
        <option ng-repeat="category in categories" value="{{category.id}}">{{category.id}}</option>
    </select>
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Category</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="record in records | filter:filter">
                <td>{{record.title}}</td>
                <td>{{record.categoryId}}</td>
            </tr>
        </tbody>
    </table>
</div>

控制: -

function MyCtrl($scope) {
    $scope.categories = [
        {id: 1},
        {id: 2},
        {id: 3}
    ];

    $scope.filter = {categoryId: "!!"};

    $scope.records = [
        {title: "I'm in category #1!", categoryId: 1},
        {title: "Category 1 is for suckas. #2 ya'll!", categoryId: 2},
        {title: "Three is best", categoryId: 3}
    ];
}

答案 4 :(得分:0)

<div class="col-md-3 col-sm-6" ng-repeat="item in listings | filter: filtername ? filtername:''">

使用这种类型的过滤器将首先检查过滤器名称是否为null或某个值,然后将采取进一步的措施。我认为这将是最简单的方法。