我是angularjs的新手,仍然在学习东西。我下面有这段代码。我的目标是将数据从数据库加载到下拉列表中。例如,数据库中的数据为New Construction
,我想从LoadDropdown
函数中加载所有数据,而New Construction
被选择为默认值。
HTML
<select name="ScopeofWork" class="form-control" ng-model="drpScopeWork" ng-options="SoW as SoW.label for SoW in ScopeOfWorkList">
<option value="" selected hidden></option>
</select>
JS
function LoadDropdown() {
$scope.ScopeOfWorkList = [{ value: 'New Construction', label: 'New Construction' },
{ value: 'Erection', label: 'Erection' },
{ value: 'Addition', label: 'Addition' },
{ value: 'Renovation', label: 'Renovation' },
{ value: 'Repair', label: 'Repair' }];
}
fnLoadDropdown();
function fnLoadDropdown() {
var url = '/AccessoryGroundPreparation/LoadScopeofWork';
$http({
method: "post",
url: url,
//data: { "ScopeOfWork": ScopeOfWork, "projectID": projectID }
}).then(function (res) {
var data = res.data;
if (data.data == null)
LoadDropdown();
else {
// $scope.drpScopeWork = $scope.ScopeOfWorkList[0];
$scope.drpScopeWork = data.data;
}
});
}
答案 0 :(得分:0)
使用ng-init
为模型的drpScopeWork
形式(如0
的数组的ng-init="drpScopeWork = ScopeOfWorkList[0].value"
索引)分配一个值
这是工作代码段:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.ScopeOfWorkList = [{
value: 'New Construction',
label: 'New Construction'
},
{
value: 'Erection',
label: 'Erection'
},
{
value: 'Addition',
label: 'Addition'
},
{
value: 'Renovation',
label: 'Renovation'
},
{
value: 'Repair',
label: 'Repair'
}
];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<select name="ScopeofWork" class="form-control" ng-model="drpScopeWork" ng-options="SoW.value as SoW.label for SoW in ScopeOfWorkList" ng-init="drpScopeWork = ScopeOfWorkList[0].value">
</select>
</div>
</div>