Digital Ninja
Digital Ninja

Reputation: 3731

Why does Angular add an empty <option> if the value exist in the provided options?

I have read on many occasions that Angular tends to add an empty option at the beginning of the select element if the value of the model does not exist among the offered options.

However, I have a model whose value is set to 0 from the start, and 0 is provided as one of the options in the select element as well, yet there is still one empty option above my own options. It disappears after the actual option whose value is 0 gets selected.

Why is this and how do I get rid of it?

A very simple example of the problem I am experiencing is displayed here: http://jsfiddle.net/yuvnz7wr/

The javascript code:

var app = angular.module('Module', []);
app.controller('Test', function ($scope) {
    $scope.model = 0;
    $scope.options = [{
        id: 0,
        name: 'Zero'
    }, {
        id: 1,
        name: 'One'
    }];
});

The HTML code:

<div ng-app="Module">
    <div ng-controller="Test as test">{{model}}
        <select ng-model="model">
            <option ng-repeat="option in options" ng-value="option.id">{{option.name}}</option>
        </select>
    </div>
</div>

Upvotes: 1

Views: 174

Answers (1)

valverde93
valverde93

Reputation: 1698

You better use ng-options and ng-init directives for <select> with angular:

<div ng-app="Module">
    <div ng-controller="Test as test">{{model}}
        <select ng-model="model" ng-init="model = options[0].id" ng-options="option.id as option.name for option in options"></select>
    </div>
</div>

Upvotes: 2

Related Questions