Juljan Juljan - 3 months ago 11
AngularJS Question

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 ?

Answer

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.