K Anbuganesh
K Anbuganesh

Reputation: 21

angular js select box comes empty option at first

I am using angular 1.6.4 I want to display ages in select box so get values from controller, I use below code, but first field will come empty? please help me how to solve it

  <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>

Upvotes: 0

Views: 272

Answers (2)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

the first option comes empty because you did not select a ngModel. add value to ngModel and also use ng-options instead 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>

Upvotes: 1

Shiladitya
Shiladitya

Reputation: 12181

You can simply use ng-init like this

<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>

Upvotes: 0

Related Questions