Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: How to include empty option in select when using ng-option

Tags:

How can I add empty option in the beginning when I use ng-option to provide predefined list of options which doesn't include empty one?

An example in jade

select(ng-model="property.Value", ng-options="item.Value as item.Name for item in property.Choices") 
like image 373
Sergiy Seletskyy Avatar asked Mar 27 '13 01:03

Sergiy Seletskyy


People also ask

Why angular dropdown automatically adds an empty value?

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-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.

How do I filter with Ng-options?

In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.

How do I set default value in ng-options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.

What is the difference between ng-repeat and Ng-options?

ng-options is the directive which is designed specifically to populate the items of a dropdown list. One major advantage using ng-options for the dropdown is, it allows us to pass the selected value to be an object. Whereas, using ng-repeat the selected value can only be string.


1 Answers

Just add an option with empty value inside of the select.

select(ng-model="property.Value", ng-options="item.Value as item.Name for item in property.Choices")   option(value="") 

Here's an example - http://jsfiddle.net/sseletskyy/uky9m/1/

like image 166
Sergiy Seletskyy Avatar answered Sep 29 '22 14:09

Sergiy Seletskyy