Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS null value for select

I couldn't find an elegant way for setting null values with a <select> using AngularJS.

HTML :

<select ng-model="obj.selected">   <option value=null>Unknown</option>   <option value="1">Yes</option>   <option value="0">No</option> </select>  {{obj}} 

JS :

$scope.obj ={"selected":null}; 

When the page is loaded, the first option is selected, which is good, and the output is {"selected":null}. When that first option is reselected after having switch to another one, the output becomes {"selected":"null"} (with the quotes), which is not what I would expect.

Running example : http://plnkr.co/edit/WuJrBBGuHGqbKq6yL4La

I know that the markup <option value=null> is not correct. I also tried with <option value=""> but it corresponds to an empty String and not to null : the first option is therefore not selected and another option which disappears after the first selection is selected by default.

Any idea ?

like image 751
Juljan Avatar asked May 15 '14 18:05

Juljan


People also ask

Can I use ngModel for select?

In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.

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.

What does select do in Angular?

Overview. HTML select element with AngularJS data-binding. The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.

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.


1 Answers

This should work for you:

Controller:

  function MyCntrl($scope) {     $scope.obj ={"selected":null};     $scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]   } 

Template:

  <div ng-controller="MyCntrl">      <select ng-model="obj.selected"             ng-options="value.id as value.value for value in objects">             <option value="">Unknown</option>     </select>  <br/>      {{obj}}   </div> 

Working plnkr

You should use ng-options with select.

like image 112
Wawy Avatar answered Oct 08 '22 12:10

Wawy