【发布时间】:2013-10-16 14:02:35
【问题描述】:
到目前为止,我看到的正常解决方案都没有奏效。我的控制器从服务返回选项列表并填充选择元素没有任何问题,但我无法设置默认值。我最接近的返回错误:Cannot read property '0' of undefined,代码为$scope.new_account.account_type = $scope.new_account.account_type[0];。有了这个错误,我认为对象还没有准备好,所以我使用了一个解析来返回我的服务数据。
.when('/accounts/new/', {
controller: function ($scope, accountTypes) {
$scope.accountTypes = accountTypes;
$scope.new_account.account_type = accountTypes[0];
},
resolve: {
accountTypes: function (AccountService) {
return AccountService.getAccountTypes();
}
}
})
但这与类似的解决方案并没有产生任何影响。选择元素被填充,但默认选项为空白。我宁愿设置一个默认选项,而不是使用带有? 值的“请选择”默认值。
我也试过
controller: function ($scope, AccountService) {
$scope.accountTypes = AccountService.getAccountTypes();
}
通过 $scope 和 ng-init 的各种实现...
<select ng-model="new_account.account_type" ng-options="type.id as type.name for type in accountTypes"
ng-init="new_account.account_type='General'">
ng-init="new_account.account_type.name='General'">
ng-init="new_account.account_type=0">
有什么想法可以帮助为此设置默认值吗?
根据要求,accountTypes 返回[{"id":1, "name":"General"}, {"id":2, "name":"Super"}, {"id":3, "name":"Trial"}
【问题讨论】:
-
你能发布 Fiddle/Plunker 吗?
-
或发帖
$scope.accountTypes模特 -
这很棘手,但它应该可以工作:)
-
var data = AccountService.getAccountTypes(); $scope.mydefault = data.shift(); $scope.accountTypes = 数据;
标签: angularjs ng-options