Search code examples
angularjsng-options

ng-option default value always blank


I cannot for the life of me set the default value for my select. It's always blank. Ugh.

<div ng-controller="quickComposeController">
    <div id="QuickComposeEmail">
        <form id="quickComposeForm">
            <div class="modal-header">
                <h3>Set email preferences</h3>
            </div>
            <div class="modal-body">
                <select ng-init="selected=selected[0]" ng-model="selected" ng-options="o.value as o.name for o in optionsObject">

                </select>
            </div>
            <div class="modal-footer">
                <input class="btn btn-success" type="submit" value="Compose Email">
                <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">Close</button>
            </div>
        </form>
    </div>
</div>

Here's my controller:

app.controller('quickComposeController', ['$scope', function($scope){

    $scope.selected = [{name : "Use Default Mail Client", value : "mailto"}];

    $scope.optionsObject = [
        {name : "Use Default Mail Client", value : "mailto"},
        {name : "Gmail", value : "gmail"},
        {name : "Yahoo", value : "yahoo"},
        {name : "Hotmail", value : "hotmail"},
        {name : "AOL", value : "aol"}
    ]

}]);

I'm only writing this down at the bottom because stackoverflow is telling me my post is mostly code and I need more text. Have a wonderful day everyone!


Solution

  • Your select should be:

    <select ng-init="selected=selected[0].value" ng-model="selected" ng-options="o.value as o.name for o in optionsObject">
    

    Here's the associated plunkr.

    The point to note is that you have to specify not only the right index but also the value property in it, since your options are based on value.