user1292807
user1292807

Reputation: 1

Angular JS select tag ng model gives one empty option Issue

Using ng-model and ng-options properties I bind select html tag. It properly bind all the data in options BUT one empty option is bind at first with " ". I want to remove this empty option using angular

<select class="ng-pristine UserGroups selectGroupClass"  ng-model='groupList' required ng-options='item.name for item in groupOptions track by item.name'></select>

$scope.groupOptions = [{ name: "What's Hot", value: 'latest' }, { name: 'Trending', value: 'popular' }];

Upvotes: 0

Views: 102

Answers (4)

User2
User2

Reputation: 1293

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options.

If you want to remove this empty option using angular select an initial value in your controller,

$scope.groupList = $scope.groupOptions[0];

Please check working example : Here

OR

You can add

<option style="display:none" value="">select a type</option>

In HTML

<select class="ng-pristine UserGroups selectGroupClass"  ng-model='groupList' required ng-options='item.name for item in groupOptions track by item.name'>
  <option ng-hide="true" value="">Select a Type</option>
</select>

Please check working example here : Demo for 2nd option

Upvotes: 2

Michal Kucaj
Michal Kucaj

Reputation: 691

Try this solution

   <select ng-model="selected" ng-options="item as item.name for item in groupOptions">
    <option value="">Choose</option>}
   </select>
<div data-ng-bind="selected.name"></div>

Upvotes: 0

Viral Shah
Viral Shah

Reputation: 47

one of the items has a blank name is what I can think of! Just verify that if possible.. Use item.someOtherproperty for item if possible to debug that :)

Upvotes: 0

Michal Kucaj
Michal Kucaj

Reputation: 691

track by just helps Angular internally with array sorting and prevent duplicated items in array. The value of the options is defined by the first argument (in your case item). If you want it to be by id then you should use item as item.name for item in groupOptions

Upvotes: 0

Related Questions