Remove Blank option from Select Option with AngularJS
Solution 1:
For reference : Why does angularjs include an empty option in select?
The empty
option
is generated when a value referenced byng-model
doesn't exist in a set of options passed tong-options
. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.
Change your code like this
var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
$scope.feed = {};
//Configuration
$scope.feed.configs = [
{'name': 'Config 1',
'value': 'config1'},
{'name': 'Config 2',
'value': 'config2'},
{'name': 'Config 3',
'value': 'config3'}
];
//Setting first option as selected in configuration select
$scope.feed.config = $scope.feed.configs[0].value;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<!-- <select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select> -->
<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
</select>
</div>
</div>
Working JSFiddle Demo
UPDATE (Dec 31, 2015)
If You don't want to set a default value and want to remove blank option,
<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
<option value="" selected="selected">Choose</option>
</select>
And in JS no need to initialize value.
$scope.feed.config = $scope.feed.configs[0].value;
Solution 2:
While all the suggestions above are working, sometimes I need to have an empty selection (showing placeholder text) when initially enter my screen. So, to prevent select box from adding this empty selection at the beginning (or sometimes at the end) of my list I am using this trick:
HTML Code
<div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs" placeholder="Config">
<option value="" selected hidden />
</select>
</div>
</div>
Now you have defined this empty option, so select box is happy, but you keep it hidden.