Angular JS过滤单值

时间:2015-09-17 15:04:27

标签: javascript angularjs

以下是我的尝试:

<section data-ng-controller="HomeController">
<table ng-repeat="item in servers | unique:'_id.idc'">
<tr>
<td> {{ item._id.idc }} </td>
</tr>
<tr ng-repeat="data in servers | filter:{_id.idc: 'LH5'}: true ">
  <td>{{data}}</td>
</tr>
</table>

这是当前的输出:

LH8
LH5
AMS 

如果我删除过滤器,请参阅{{data}}

中的一些示例
{"_id":{"cluster":0,"idc":"LH8"},"Physical":{"SumCores":488,"SumMemory":3232},"Virtual":{"SumCores":2,"SumMemory":8}}
{"_id":{"cluster":1,"idc":"LH8"},"Physical":{"SumCores":256,"SumMemory":1024},"Virtual":{"SumCores":232,"SumMemory":469}}

为什么不正确过滤?独特的作品完美无缺,但单过滤器却没有。

编辑:我还检查了这个唯一过滤器是否与它有些冲突,但如果没有安装过滤器,它仍无效。

6 个答案:

答案 0 :(得分:1)

Your filter is not formatted correctly for nested objects. It should be:

ng-repeat="data in servers | filter: { _id: { idc: 'LH5' } }"

A working, simplified example is below.

var myApp = angular.module('MyApp', []);
		
myApp.controller('MyController', ['$scope', function($scope) {
    $scope.filter = 'red';
    $scope.cars = [
        {
            make: 'Ford',
            model: 'Focus',
            year: '2012',
            colors: {
            	interior: 'red',
                exterior: 'blue'
            }
        },
        {
            make: 'Ford',
            model: 'Fusion',
            year: '2009',
            colors: {
            	interior: 'green',
                exterior: 'black'
            }
        },
        {
            make: 'Honda',
            model: 'Civic',
            year: '2011',
            colors: {
            	interior: 'red',
                exterior: 'silver'
            }
        }
    ]
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<div ng-app="MyApp" ng-controller="MyController">
    <label for="filter">Interior color filter: </label>
    <input type="text" ng-model="filter" id="filter" />
    <div ng-repeat="car in cars | filter: { colors: { interior: filter } }">{{ car.year }} {{ car.make }} {{ car.model }}</div>
</div>

答案 1 :(得分:0)

首先添加数据,如

    <tr ng-repeat="data in servers | filter:{data.idc : 'LH5'}">
      <td>{{data}}</td>
    </tr>

答案 2 :(得分:0)

如果您想以自己的方式使用,则需要从here添加一个JS文件

有关详细信息,请参阅此question

答案 3 :(得分:0)

从您的示例中我假设您的数据结构如下所示:

data: {
    propA: 'A',
    proB: 'B',
    _id: {
        idc: 'LH5'
    }
}

您的问题是您正在尝试匹配您正在迭代的对象的子属性。

来自文档:

  

请注意,命名属性将匹配同一级别的属性   只有,而特殊的$属性将匹配相同的属性   等级或更深。例如。一个数组项,如{name:{first:&#39; John&#39;,last:   &#39; Doe&#39;}}将不会被{name:&#39; John&#39;}匹配,但将被匹配   {$:&#39; John&#39;}。

所以我试试:

<tr ng-repeat="data in servers | filter:{$: 'LH5'}: true ">
  <td>{{data}}</td>
</tr>

http://jsfiddle.net/kb598pby/

答案 4 :(得分:0)

您正在按嵌套属性进行过滤,传递给过滤器的表达式不会计算为有效的javascript对象。你应该这样做:

<tr ng-repeat="data in servers | filter:{_id: [{idc: 'LH5'}]}">

答案 5 :(得分:0)

请阅读以下参考资料

对于AngularJs中的过滤器单值

http://toddmotto.com/everything-about-custom-filters-in-angular-js/

我希望它可以帮到你