我花了一个小时尝试了所有可以想象的属性排列,将select作为对象绑定到模型, ng-selected 什么都不做。
<select ng-model="localModel.priceType">
<option
ng-repeat="item in vm.priceTypes"
ng-selected="localModel.priceType == item"
ng-value="item"
>{{item.name}}</option>
</select>
或
<select ng-model="localModel.priceType">
<option
ng-repeat="item in vm.priceTypes"
ng-selected="localModel.priceType.id == item.id"
ng-value="item"
>{{item.name}}</option>
</select>
或
<select ng-model="localModel.priceType">
<option
ng-repeat="item in vm.priceTypes track by item.name"
ng-selected="localModel.priceType.name == item.name"
ng-value="item"
>{{item.name}}</option>
</select>
选择列表正确呈现,选项值看起来很时髦,即“对象:875”。和选择不起作用。
我需要ng-model作为对象,而不是object.someId。
使用ng-options代替&lt; option&gt;解决了这个问题。 NG-repat
<select ng-model="localModel.priceType" ng-options="item as item.namefor item in vm.priceTypes track by item.name"></select>
答案 0 :(得分:2)
ngValue需要ngValue的字符串。要将ngRepeat与<option>
标记一起使用,请使用value="{{item}}"
代替ng-value。展开下面的代码段,看它是否有效。
angular.module('myApp', [])
.controller('ctrl', function($scope) {
$scope.vm = {
priceTypes: [{
id: 3,
name: 'pound'
},
{
id: 5,
name: 'Yen'
},
{
id: 6,
name: 'dollar'
}
]
};
//select model value
$scope.localModel = {
priceType: $scope.vm.priceTypes[1]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="localModel.priceType">
<option
ng-repeat="item in vm.priceTypes as item"
ng-selected="localModel.priceType.id == item.id"
value="{{item}}"
>{{item.name}}</option>
</select>
<div>
priceType: {{ localModel.priceType }}
</div>
</div>
更简单的方法是在<select>
标记上使用ngOptions,并使用表单组合:
select as label for value in array track by expr
有关详细信息,请参阅Usage下参数部分中的 comprehension_expression 表单。
angular.module('myApp', [])
.controller('ctrl', function($scope) {
$scope.vm = {
priceTypes: [{
id: 3,
name: 'pound'
},
{
id: 5,
name: 'Yen'
},
{
id: 6,
name: 'dollar'
}
]
};
//select model value
$scope.localModel = {
priceType: $scope.vm.priceTypes[1]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="localModel.priceType" ng-options="item as item.name for item in vm.priceTypes track by item.name">
</select>
<div>
priceType: {{ localModel.priceType }}
</div>
</div>
答案 1 :(得分:0)
https://docs.angularjs.org/api/ng/directive/ngSelected
ngSelected
不与select
和ngModel
互动 指令,它只在元素上设置selected
属性。如果你 在select上使用ngModel
时,您不应该使用ngSelected
选项,因为ngModel
将设置选择值和选定的选项。
尝试
<select ng-model="localModel.priceType">
<option ng-repeat="item in vm.priceTypes track by item.name"
ng-value="item.name">
{{item.name}}
</option>
</select>
您可以将ng-value
更改为vm.priceTypes[0]
所需的任何值。