我有一个与此类似的对象:
$scope.division = [
{
name: "Tom",
number: 1
},
{
name: "Greg",
number: 2
}
];
现在在我的HTML中,我使用ngOption
显示填充了对象值的下拉列表。
<select data-ng-model="game.player1" data-ng-options="player.name for player in division">
<option value="" disabled="true">Player 1</option>
</select>
按预期显示名称下拉列表。但是,我想在下拉列表中显示名称和数字。例如,如果我对其进行硬编码:
<option>1 - Tom</option>
<option>2 - Greg</option>
我尝试了各种方法,包括这样的内容:
data-ng-options="player.number player.name for player in division"
但似乎没有任何效果。
答案 0 :(得分:3)
你应该能够像这样连接:
ng-options="(player.number + ' - ' + player.name) for player in division"
答案 1 :(得分:2)
你可以在表达式本身中连接它。
<select data-ng-model="game.player1"
data-ng-options="(player.number + '-' + player.name) for player in division">
但是我会在控制器上执行此操作以创建需要绑定的特定视图模型,而不是在视图上执行此操作。
angular.module('app', []).controller('ctrl', function($scope){
$scope.game ={player1: 1};
$scope.division = [
{
name: "Tom",
number: 1
},
{
name: "Greg",
number: 2
}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select data-ng-model="game.player1" data-ng-options="player.number as (player.number + '-' + player.name) for player in division">
<option value="" disabled="true">Player 1</option>
</select>
{{game.player1}}
</div>
答案 2 :(得分:1)
尝试使用控制器中定义的格式化功能:
$scope.format = function(player) {
return player.number + ' - ' + player.name;
};
然后将其标记为:
data-ng-options="format(player) for player in division"