Search code examples
angularjsnullhtml-selectng-options

select with a null value


Is it possible to render correctly a select, with a few options which one value is null?

I will provide a simple example:

$scope.value = null;
$scope.list = [{ id: null, description: "none"},
    { id:1, description: "one" },
    { id:2, description: "two" },
    { id:3, description: "three" }];

html:

<select ng-model="value" ng-options="item.id as item.description for item in list">
</select>

Plunker: http://plnkr.co/edit/ECQ3XUnv75sJW4Ix8IyO

After rendering everything is ok (none is selected), but when I click into select there is one additional option - empty (and while $scope.value is null the "empty" options remains). When I choose other option and while $scope.value is not null everything seems to work. Is there some kind a way to remove the empty option that browser generates while model is null?

This behaviour is the same on Firefox, Chrome and Safari.


Solution

  • You don't have to add meaningless null-options manually. You just need to add empty option into HTML:

    <select ng-model="value" ng-options="item.id as item.description for item in list">
        <option value="">none</option>
    </select>
    

    Controller:

    $scope.list = [
        { id:1, description: "one" },
        { id:2, description: "two" },
        { id:3, description: "three" }
    ];
    

    Demo: http://plnkr.co/edit/8j9NUT3rUfwUj4QJhZqa?p=preview