【问题标题】:AngularJS filter nested ng-repeat based on repeated object propertiesAngularJS 根据重复的对象属性过滤嵌套的 ng-repeat
【发布时间】:2014-10-14 13:12:54
【问题描述】:

我有一组餐厅对象,我想通过对他们的城市进行分组来列出它们

我的对象是这样的;

restaurant = {
     id: 'id',
     name: 'name',
     city: 'city'
}

这个 HTML 标记可以提供一些关于我想要做什么的信息。

 <div ng-repeat="restaurant in restaurant | filter: ???">
        <div class="header">
            <h1 ng-bind="restaurant.city"></h1>
            <a>Select All</a>
        </div>
        <div class="clearfix" ng-repeat="???">
            <input type="checkbox" id="restaurant.id" />
            <label ng-bind="restaurant.name"></label>
        </div>
    </div>

我可以用一个数组来做,还是需要创建单独的城市和餐厅数组来做?

【问题讨论】:

  • 您想按城市对您的餐厅数组进行分组吗?
  • 是的,这正是我想要做的 =)

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


【解决方案1】:

如果你想按城市对餐厅进行分组,可以使用angular.filter模块的groupBy。

只需将此处的 JS 文件:http://www.cdnjs.com/libraries/angular-filter 添加到您的项目中并使用以下代码。

var myApp = angular.module('myApp',['angular.filter']);

function MyCtrl($scope) {    
    $scope.restaurants = [
       {id: 1, name: 'RestA', city: 'CityA'},
       {id: 2, name: 'RestB', city: 'CityA'},
       {id: 3, name: 'RestC', city: 'CityC'},
       {id: 4, name: 'RestD', city: 'CityD'}
    ];
}

<div ng-controller="MyCtrl">
    <ul ng-repeat="(key, value) in restaurants | groupBy: 'city'">
        <b>{{ key }}</b>
      <li ng-repeat="restaurant in value">
          <i>restaurant: {{ restaurant.name }} </i>
      </li>
    </ul>
</div>

我已经为您创建了 JSFiddle 并提供了工作示例。

【讨论】:

  • 完美。按预期工作
猜你喜欢
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多