Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS select creates option with value "? object:null ?" and doesn't use empty default option when bound to null

Tags:

angularjs

Here's what the code looks like

<select ng-model="nullableInt">
  <option></option>
  <option value="0">First option</option>
  <option value="1">First option</option>
  <option value="2">First option</option>
</select>

When nullableInt is null the generated html is

<select ng-model="nullableInt">
  <option></option>
  <option value="? object:null ?"></option>
  <option value="0">First option</option>
  <option value="1">First option</option>
  <option value="2">First option</option>
</select>

Reproduced in the plunkr here: http://plnkr.co/edit/05pBEMJppmkrn3nFgYdk?p=info

It's worth mentioning that I'm trying to avoid using ng-options, it seems like a bit of overkill to create an endpoint for AngularJS to consume some data that really will not change very often, if ever.

like image 327
MushinNoShin Avatar asked May 14 '14 00:05

MushinNoShin


People also ask

Why does AngularJS include an empty option in select?

1 Answer. The reason why AngularJS include an empty option in select is that it is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options.

How do I set default selected 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 does it mean when the value of the selected menu option is an empty string?

</option> , value="" is turned into just value . The value, when set to the empty string is simply discarded.

What is ng-options?

The ng-options Directive in AngularJS is used to build and bind HTML elements with options to a model property. It is used to specify <options> in a <select> list. It is designed specifically to populate the items on a dropdown list. This directive implements an array, in order to fill the dropdown list.


1 Answers

Update 3/29/2017:

As Jorge Rodrigues dos Santos stated, this should be handled in a different way for newer versions of angular. Below is taken from the current documentation for angular 1.6.3

Optionally, a single hard-coded element, with the value set to an empty string, can be nested into the element. This element will then represent the null or "not selected" option. See example below for demonstration.

https://docs.angularjs.org/api/ng/directive/select


Angular is creating a new option to represent the null value. It didn't find one of the options you provided in the HTML.

To bind to null, set the value="null" on the first option

<option value="null"></option>

http://plnkr.co/edit/kzPVu4hiMcP6wA6crGYt?p=preview

like image 74
dmullings Avatar answered Nov 15 '22 23:11

dmullings