如果我想设置组合框的值,我试过这个:
controllercode:
$scope.streettypeMockData = [{
name: 'Street',
value: 'Street'
}, {
name: 'Avenue'
}, {
name: 'Crescent'
}, {
name: 'Drive'
}, {
name: 'Road'
}, {
name: 'Highway'
}];
var sel = "Street";
var selectedValue = {
name: sel
};
$scope.streetTypeSelected = selectedValue;
谁能告诉我为什么这不起作用?另见http://plnkr.co/edit/4ISL8A1cNGCtafsc0leX?p=preview
答案 0 :(得分:0)
您可以像这样简单地使用ng-init
<select ng-init="streetTypeSelected = streettypeMockData[0]" class="form-control" ng-model="streetTypeSelected" ng-options="streetType.name for streetType in streettypeMockData">
</select>
<强> Working Demo 强>
你也可以这样做,如下所示
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.streettypeMockData = [
{name: 'Street', value: 'Street'},
{name: 'Avenue'},
{name: 'Crescent'},
{name: 'Drive'},
{name: 'Road'},
{name: 'Highway'}
];
$scope.streetTypeSelected = $scope.streettypeMockData[0];
});
<强> Working Demo 强>
另外看看这个
答案 1 :(得分:0)
代码有一些问题:
ng-options
选择名称,而ng-model
指向对象。最好使用streetType as streetType.name for streetType in streettypeMockData
来选择整个对象。track by
。完整<select>
应为:
<select class="form-control" ng-model="streetTypeSelected"
ng-options="streetType as streetType.name for streetType in streettypeMockData track by streetType.name">
请参阅forked plunker。