我需要一种按其属性排序列表的方法。
我有这个傻瓜: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>
答案 0 :(得分:5)
首先,对于这样的事情,我更喜欢使用radio
而不是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";
STEVE HOLT!
答案 1 :(得分: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
*球员:基因
集团名称:beta
*球员:乔治
*球员:保拉郎
组名:伽马
*球员:史蒂夫
*球员:Scruath
更新: jsbin