lancey lancey - 1 year ago 216
AngularJS Question

ng-selected not working in select field

I am trying to set the default value of a select field to a set option but its not working and I can't seem to figure out what am I doing wrong?

In my controller I have:

$scope.interp_id = "2"; // set the default id
.then(function (response) {
$scope.interpreters =;

get.php is a php file that returns json (this is working properly).

My select looks like:

<select ng-model="interpreters_id">
<option ng-repeat="x in interpreters" value="{{}}" ng-selected="{{ == interp_id}}">{{x.first_name}} {{x.middle_name}} {{x.last_name}}</option>

When I go to view it in my browser it looks like:
enter image description here
enter image description here

but when I inspect the element it shows that option ng-selected is True.

enter image description here

what am I doing wrong?

Answer Source

ngOptions is the recommended way to use select elements in Angular.

Also, if you look at the ngSelected documentation there is a yellow box that states that it does not work properly with the select and ngModel properties which is, in a way, what you are trying to do.

ngRepeat will gladly repeat your option elements however it is not the correct way to work with a select element.

I have prepared a fiddle for you to try it out.

<div ng-app="ngOptionsApp">
    <div ng-controller="ExampleController">
        <select ng-model="selectedInterpreter" ng-options="interpreter as for interpreter in interpreters track by">
            <option value="">Select an Interpreter</option>


angular.module('ngOptionsApp', []).controller('ExampleController', ['$scope', function($scope) {
    $scope.interpreters=[{id: 1, name:'Gill Bates'}, {id: 2, name:'Cohn Jarmack'}, {id: 3, name:'Melon Musk'}];
    $scope.selectedInterpreter = $scope.interpreters[0];

Hope it helps ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download