我需要在控制器中填充模板html文件中的select(option)元素。我可以成功完成,但不能给出默认值(以避免第一个空选项)
template.html文件
...
<select name="drill_down" id="drill_down" ng-model="drill_down"
ng-options="item.value for item in items"></select>
...
controller.js文件
(function () {
'use strict';
var app = angular.module('appname', []);
app.config(function($stateProvider) {
$stateProvider
.state('appname', {
url: '/appname',
templateUrl: '/appname/template.html',
controller: 'AppCtrl'
});
});
app.controller('AppCtrl', AppCtrl);
function AppCtrl($scope, MyService) {
$scope.college_majors_full = [];
$scope.job_title_functions = [];
MyService.getData().then(function(rows) {
$scope.items = rows; // this works - populates select options
$scope.drill_down = $scope.items[0].value; // this doesn't work
});
...
有任何帮助吗?感谢。
答案 0 :(得分:1)
您的选项只包含商品的文字属性
您正在分配值而不是ID
试试这个
$scope.drill_down = $scope.items[0].value;
或者您可以在选项
中创建值文本类型试试这个
查看
<select name="drill_down" id="drill_down" ng-model="drill_down"
ng-options="item.id as item.value for item in items"></select>
<强>控制器强>
$scope.drill_down = $scope.items[0].id;
答案 1 :(得分:0)
您应该可以通过ngModel
设置默认值。有关为ngOption
设置默认值的信息,请参见this answer:
var app = angular.module('optionsApp', []);
app.controller('optionsCtrl', function($scope) {
$scope.prop = {
"type": "select",
"name": "Service",
"value": "Service 3",
"values": ["Service 1", "Service 2", "Service 3", "Service 4"]
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="optionsApp">
<div ng-controller="optionsCtrl">
<select ng-model="prop.value" ng-options="v for v in prop.values"></select>
</div>
</div>
&#13;