簡體   English   中英

角js選擇框首先為空選項

[英]angular js select box comes empty option at first

我正在使用角度1.6.4,我想在選擇框中顯示年齡,以便從控制器獲取值,我使用下面的代碼,但是第一個字段將為空? 請幫我解決

  <select ng-model="agefrom" name="agefrom" id="agefrom" class="select" style="width: 45%">
    <option ng-repeat="age in ages" ng-value="age">{{age}}</option>
  </select>

第一個選項為空,因為您沒有選擇ngModel。 ngModel添加值,也可以使用ng-options代替ng-repeat

 angular.module("app",[]) .controller("ctrl",function($scope){ $scope.ages = [2,3,4]; $scope.agefrom = $scope.ages[0] }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <select ng-model="agefrom" name="agefrom" id="agefrom" class="select" style="width: 45%" ng-options="age as age for age in ages"> </select> </div> 

您可以像這樣簡單地使用ng-init

<select ng-init="agefrom = ages[0]" 
    ng-model="agefrom" 
    name="agefrom" id="agefrom" class="select" 
    style="width: 45%">
    <option ng-repeat="age in ages" ng-value="age">{{age}}</option>
</select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM