按Angular.js中的公共对象属性过滤数组?

时间:2015-06-13 14:23:42

标签: javascript arrays json angularjs filter

我在几个小时内一直在努力。情况是,我有一个应用程序,它接收有关这种JSON格式的人的数据:

"people": [
      {
        "name": "Ivan",
        "city": "Moscow",
        "country": "Russia"
      },
      {
        "name": "John",
        "city": "Seattle",
        "country": "United States"
      },
      {
        "name": "Michael",
        "city": "Seattle",
        "country": "United States"
      }
    ]

我需要根据他们的城市将它们分组(显示在下拉列表<ul>中。即,用户点击“西雅图”,并显示约翰和迈克尔的<li>

如何做到这一点?

4 个答案:

答案 0 :(得分:3)

app.controller('FooCtrl', function($scope) {
   $scope.people = [
      {
        "name": "Ivan",
        "city": "Moscow",
        "country": "Russia"
      },
      {
        "name": "John",
        "city": "Seattle",
        "country": "United States"
      },
      {
        "name": "Michael",
        "city": "Seattle",
        "country": "United States"
      }
    ];
});

你可以像这样过滤它:

<div ng-repeat="person in people | filter:{ city: 'Seattle' }">

对于动态搜索:

<div ng-app="demo" ng-controller="FooCtrl"><input type="text" ng-model="search.city" >
  <ul>
     <li ng-repeat = "person in people | filter: search"> {{person.name}</li>
  </ul>
</div>

working example

如果您只使用搜索作为ng模型,它将过滤整个对象。但是当我使用search.city时,它只过滤那个字段。

答案 1 :(得分:2)

使用angular-filter进行分组。您的视图代码如下所示:

<ul ng-repeat="(key, value) in people | groupBy: 'city'">
  City: {{ key }}
  <li ng-repeat="person in value">
    person: {{ person.name }} 
  </li>
</ul> 

这是Plunker

答案 2 :(得分:1)

您可以将过滤器置于选择选项中,该选项限制用户选择来自服务器的一个城市。 https://jsfiddle.net/4bhjm5vu/

app.js:

<div ng-app="myApp">
    <div ng-controller="FooCtrl">
        <select name="city" ng-model="selectedCity" data-ng-options="person.city as person.city for person in people | unique:'city'"><option data-ng-disabled='true' value="">City</option>
        </select>

        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>City</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="person in people | filter: {city: selectedCity}">
                    <td>{{person.name}}</td>
                    <td>{{person.city}}</td>
                    <td>{{person.country}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

HTML:

findall

答案 3 :(得分:0)

你可以尝试,

<input type="text" ng-model = "search.city" >
<ul>
  <li ng-repeat = "people in peoples | filter: search"> {{people.name}}      </li>
</ul>

请参阅此插件,http://plnkr.co/edit/SxcorUe1uAszY9FqBJXd?p=preview