AngularJS在有效的ajax数据到达之前设置虚拟选项元素

时间:2014-11-10 13:21:46

标签: javascript angularjs

据我所知,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];

1 个答案:

答案 0 :(得分:3)

您可以为$ scope.ENVIRONMENTS数组添加临时值,即:

 $scope.ENVIRONMENTS = [{name:"Please wait"}];

并在从您支持的

获取数据后将其删除
$scope.ENVIRONMENTS.shift()

请参阅下面的演示

&#13;
&#13;
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;
&#13;
&#13;