Remove Empty Item From Select Drop Down Angularjs
I'm trying to bind data to select drop down using AngularJS ng-repeat directive but it's showing an empty data on page load. How to remove the empty item. Here is the code: <
Solution 1:
make $scope.selected = 1;
as $scope.selected = "1";
it will default select a value
var app = angular.module('app',[]);
app.controller('homeCtrl',['$scope',function($scope){
$scope.selected = "1";
$scope.items=[
{name: 'harry111',id:1},
{name: 'rimmi',id:2}
];
}]);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><html><head></head><bodyng-app="app"><divng-controller="homeCtrl"><selectng-model="selected"><optionng-repeat="item in items"value="{{item.id}}">
{{item.name}}
</option></select><span>
{{selected}}
</span></div></body></html>
Solution 2:
You need to include ng-repeat
on <select>
tag like this
<html><head></head><bodyng-app="app"><divng-controller="homeCtrl"><selectng-model="selected"ng-options="value.id as value.name
for (key,value) in items"
></select><span>
{{selected}}
</span></div></body></html>
This will not add the blank option in the select dropdown. Here is the working CODEPEN
Solution 3:
Use ng-options instead,
ng-options="value.id as value.name for (key,value) in items"
DEMO
var app = angular.module('app',[]);
app.controller('homeCtrl',['$scope',function($scope){
$scope.items=[
{name: 'harry111',id:1},
{name: 'rimmi',id:2}
];
$scope.selected = $scope.items[0].id;
}]);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><html><head></head><bodyng-app="app"><divng-controller="homeCtrl"><selectng-model="selected"ng-options="value.id as value.name
for (key,value) in items"
></select><span>
{{selected}}
</span></div></body></html>
Post a Comment for "Remove Empty Item From Select Drop Down Angularjs"