Search code examples
angularjsng-options

ng-options doesn't highlight selected value on initial load


Consider a next code sample:

http://plnkr.co/edit/LA6fu1vdzRWFaQw6Zl6S?p=preview

<!DOCTYPE html>
<html ng-app="app">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="main">
  <select novalidate="" ng-model="selectedItem" ng-options="item.id as item.name for item in items track by item.id"> </select>
</body>

</html>


var app = angular.module('app', [])

.controller('main', ['$scope',function($scope) {
  $scope.items = [
    {"id":0,"name":"a"},
    {"id":1,"name":"b"},
    {"id":2,"name":"c"},
    {"id":3,"name":"d"}
  ];
  $scope.selectedItem = 1;
}])

I expect that on initial load select element will have a "b" option selected, but it doesn't. What I am doing wrong?


Solution

  • You need to:

    • use an updated version of AngularJS (Change 1.1.5 to 1.6.10 in your script)

    • remove track by item.id, it's used for ng-repeat, not ng-options

    Here is a working demo:

    var app = angular.module('app', [])
    
    .controller('main', ['$scope',function($scope) {
      $scope.items = [
        {"id":0,"name":"a"},
        {"id":1,"name":"b"},
        {"id":2,"name":"c"},
        {"id":3,"name":"d"}
      ];
      $scope.selectedItem = 1;
    }])
    <!DOCTYPE html>
    <html ng-app="app">
    
      <head>
        <meta charset="utf-8" />
        <title>AngularJS Plunker</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.js"></script>
      </head>
    
      <body ng-controller="main">
        <select novalidate=""
          ng-model="selectedItem" 
          ng-options="item.id as item.name for item in items">
        </select>
        {{selectedItem}}
      </body>
    </html>