据我所知,AngularJS在使用ng-model
指令时设置了默认值。我需要使用$http.get
检索的有效选项填充select元素。问题是,除了所有有效元素之外,我还有一个虚拟元素值?
。 如何摆脱它?
<select id="environment" name="environment_name" ng-model="environment" ng-options="e.name for e in ENVIRONMENTS" required>
</select>
$scope.ENVIRONMENTS = [];
$http.get("/getEnvironments").success(function(data){
data.forEach(function(el){
$scope.ENVIRONMENTS.push(el);
});
}).error(function (data) {
$scope.showErrorMsg("Cannot get ENVIRONMENTS.");
});
$scope.environment = $scope.ENVIRONMENTS[0];
答案 0 :(得分:3)
您可以为$ scope.ENVIRONMENTS数组添加临时值,即:
$scope.ENVIRONMENTS = [{name:"Please wait"}];
并在从您支持的
获取数据后将其删除$scope.ENVIRONMENTS.shift()
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $http) {
$scope.ENVIRONMENTS = [{
name: "Please wait"
}];
$http.get("/getEnvironments").then(function(data) {
$scope.ENVIRONMENTS.shift()
data.forEach(function(el) {
$scope.ENVIRONMENTS.push(el);
})
//set default value after you get data from backend
$scope.environment = $scope.ENVIRONMENTS[0];
}, function(data) {
$scope.showErrorMsg("Cannot get ENVIRONMENTS.");
});
$scope.environment = $scope.ENVIRONMENTS[0];
$scope.showErrorMsg = function(msg) {
console.log(msg);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<select id="environment" name="environment_name" ng-model="environment" ng-options="e.name for e in ENVIRONMENTS" required>
</select>
</div>
</div>
&#13;