0

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?

Maris
  • 4,608
  • 6
  • 39
  • 68
  • @AlekseySolovey , still doesn't work: http://plnkr.co/edit/LA6fu1vdzRWFaQw6Zl6S?p=preview – Maris Jun 04 '18 at 12:23
  • https://stackoverflow.com/questions/50483263/ng-options-key-values-in-object/50483679 check this answer. – Chiru Adi Jun 04 '18 at 12:29

1 Answers1

1

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>
Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34