AngularJs - ng-model in a SELECT

Jordumus picture Jordumus · May 5, 2015 · Viewed 139.5k times · Source

JSfiddle

Problem:

I have a SELECT-element in my page, which is filled in with an ng-repeat. It also has a ng-model which has a default value.

When I change the value, the ng-model adapts, that's ok. But the dropdown-list shows an empty slot at launch, where it should have the item with the default value selected instead.

Code

<div ng-app ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

With JS:

function myCtrl ($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

};

Answer

Patrick Evans picture Patrick Evans · May 5, 2015

You can use the ng-selected directive on the option elements. It takes expression that if truthy will set the selected property.

In this case:

<option ng-selected="data.unit == item.id" 
        ng-repeat="item in units" 
        ng-value="item.id">{{item.label}}</option>

Demo

angular.module("app",[]).controller("myCtrl",function($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>