我正在尝试通过他们的团队名称来选择一些团队。它似乎部分工作,但似乎无法让团队按顺序显示。 真的喜欢在顶部设置“All Teams”,但我不知道它有多可行。
以下是代码:
HTML
<div ng-app>
<div ng-controller="Ctrl">
<label>Filter by Team:</label>
<select ng-model="filters.teamIdSelected" ng-options="value.teamId as value.teamName for (key, value) in teams | orderBy: 'teamName'"></select>
</div>
JS
function Ctrl($scope) {
$scope.filters = {};
var teams = [{
"teamName": "Cubs",
"teamId": 51
}, {
"teamName": "Bulldogs",
"teamId": 68
}, {
"teamName": "Grizzlies",
"teamId": 12
}, {
"teamName": "Tigers",
"teamId": 71
}, {
"teamName": "Braves",
"teamId": 16
}, {
"teamName": "Cowboys",
"teamId": 24
}, {
"teamName": "Monsters",
"teamId": 70
}, {
"teamName": "Brats",
"teamId": 23
}, {
"teamName": "Chumps",
"teamId": 21
}, {
"teamName": "Dingleberries",
"teamId": 93
}, {
"teamName": "Redskins",
"teamId": 22
}, {
"teamName": "123Myteam",
"teamId": 47
}, {
"teamName": "Gophers",
"teamId": 87
}, {
"teamName": "Peanuts",
"teamId": 77
}, {
"teamName": "Bloopers",
"teamId": 79
}, {
"teamName": "Losers",
"teamId": 88
}, {
"teamName": "Marlins",
"teamId": 84
}, {
"teamName": "Ear Muffs",
"teamId": 75
}, {
"teamName": "Pizzas",
"teamId": 78
}, {
"teamName": "Weiners",
"teamId": 74
}, {
"teamName": "Bills",
"teamId": 86
}];
teams.unshift({
teamId: 0,
teamName: 'All Teams'
});
$scope.teams = teams;
$scope.filters.teamIdSelected = 0; }
这是一个fiddle来演示。
提前致谢。
答案 0 :(得分:2)
不幸的是,当比较/排序Javascript中的字符串(什么顺序)时,每个以数字字符开头的字符串都将在任何其他字符串之前。这就是为什么我建议您改变生成选择的方式并执行以下操作:
<div ng-controller="Ctrl">
<label>Filter by Team:</label>
<select ng-model="filters.teamIdSelected">
<option value="0">All Teams</option>
<option ng-repeat="team in teams | orderBy: 'teamName'" value="{{team.teamId}}">{{team.teamName}}</option>
</select>
</div>
查看工作小提琴here
答案 1 :(得分:2)
这就是你需要的:
<div ng-app>
<div ng-controller="Ctrl">
<label>Filter by Team:</label>
<select
ng-model="filters.teamIdSelected"
ng-options="team.teamName for team in teams | orderBy: 'teamName'"
><option value="">All Teams</option></select>
</div>
</div>
答案 2 :(得分:2)
你的for (key, value) in teams
正在撤消一个的排序,我认为这是为了迭代对象属性而你只有一个数组。您可以将其替换为for value in teams
:
ng-options="value.teamId as value.teamName for value in teams | orderBy: 'teamName'
Nicolas的选择很好,但这里还有几种方法。首先,您可以在“所有团队”前面放置一个空格,这将使其首先排序(fiddle):
teams.unshift({
teamId: 0,
teamName: ' All Teams'
});
其次,您可以创建一个自定义排序的函数。这个只是在其他名称前添加一个'Z'用于排序(fiddle):
$scope.sortName = function(team) {
if (team.teamName == 'All Teams')
return team.teamName;
return 'Z' + team.teamName;
};
-html -
<select ng-model="filters.teamIdSelected"
ng-options="value.teamId as value.teamName for value in teams | orderBy:sortName"
>
</select>