3

我需要一种按属性排序列表的方法。

我有这个 plunker:http: //jsfiddle.net/Tropicalista/aF2aL/1/

但不知道锄头继续。我需要一种方法来根据我在复选框中选择的内容对列表进行排序......

function myCtrl($scope){
    $scope.friends = [

    {
        name: "Michael",
        gender: "Male",
        hair: "Brunette"
    },
    {
        name: "George Michael",
        gender: "Male",
        hair: "Brunette"
    },
    {
        name: "Gob",
        gender: "Male",
        hair: "Brunette"
    },
    {
        name: "Tobias",
        gender: "Male",
        hair: "Black"
    },
    {
        name: "Lindsay",
        gender: "Female",
        hair: "Blonde"
    },
    {
        name: "Maeby",
        gender: "Female",
        hair: "Black"
    }
];
$scope.orderBy = function(target){
    $scope.groups = _.groupBy($scope.friends, target);
}
$scope.activeGroups = {};

}

这是我的html:

<input type="checkbox" ng-click="orderBy('name')" />Name
<input type="checkbox" ng-click="orderBy('gender')" />Gender
<input type="checkbox" ng-click="orderBy('hair')" />Hair

<div data-ng-repeat="(myFilter, users) in groups">
    <h2>{{myFilter}}</h2>        
    <ul>
        <li data-ng-repeat="user in users">
        {{ user.name }}
        </li>
    </ul>
</div>
4

2 回答 2

5

首先,对于这样的事情,我更喜欢使用 aradio而不是 a checkbox。它在语义上是正确的。复选框表明您可以按多个字段进行分组,并且从您的问题中看不出您正在尝试这样做。

知道了这一点,您可以像这样定义您的收音机:

<input type="radio" ng-model="grouping" value="name"  />Name
<input type="radio" ng-model="grouping" value="gender" />Gender
<input type="radio" ng-model="grouping" value="hair" />Hair

现在,您可以ng-repeat根据groupedFriends集合告诉您的分组:

<div data-ng-repeat="(group, users) in groupedFriends">
    <h2>{{group}}</h2>        
    <ul>
        <li data-ng-repeat="user in users">
            {{ user.name }}
        </li>
    </ul>
</div>

然后你的控制器只是观察grouping变量并对数据进行分组:

$scope.$watch('grouping', function() {
    $scope.groupedFriends = _.groupBy($scope.friends, $scope.grouping);
});

$scope.grouping = "gender";

这是一个工作小提琴。

史蒂夫霍尔特!

于 2013-09-09T00:56:09.450 回答
3

您可以使用 angular.filter 模块的groupBy,它很容易使用,实际上比 lodash 实现更快,请参见:link
用法: (key, val) in collection | groupBy: 'property'或者nested.property
这里是一个例子:

JS:

$scope.players = [
  {name: 'Gene', team: 'alpha'},
  {name: 'George', team: 'beta'},
  {name: 'Steve', team: 'gamma'},
  {name: 'Paula', team: 'beta'},
  {name: 'Scruath', team: 'gamma'}
];

HTML:

<ul ng-repeat="(key, value) in players | groupBy: 'team'">
  Group name: {{ key }}
  <li ng-repeat="player in value">
    player: {{ player.name }} 
  </li>
</ul>

结果:
组名:alpha
* 选手:Gene
组名:beta
* 选手:George
* 选手:Paula
组名:gamma
* 选手:Steve
* 选手:Scruath

更新: jsbin

于 2014-10-13T19:38:25.413 回答