0

I am struggling with the following piece of code.

  <body ng-controller="MainCtrl">
    <h1>Select something below</h1>
    <select id="s1" ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
    <h3>The selected item:</h3>
    <pre>{{selectedItem | json}}</pre>
    <h3>The inner html of the select:</h3>
    <pre id="options" class="prettify html"></pre>
  </body>

and in js

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { id: 1, name: 'foo' },
    { id: 2, name: 'bar' },
    { id: 3, name: 'blah' }];

  $scope.selectedItem = { id: 3, name: 'blah' };

});

I have a selected item by default. But it doesn't show up in the selection while the page loads.

I have provided my code in the following link

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

In the given example the dropdown should by default select the item blah.

TIA Mobin

Mobin Skariya
  • 392
  • 3
  • 12

3 Answers3

1

The first thing you need to do is update your angularjs version, then you can simply follow the angular select examples.

In the provided link they use track by to display the correct object, I took the liberty of editing their example plunker and added your code Here it is!

as you can see, the only thing I added to your code was track by item.id

sch
  • 1,368
  • 3
  • 19
  • 35
0

Try this:

<select id="s1" ng-model="selectedItem" ng-options="item.id as item.name for item in items"></select>

and:

$scope.selectedItem = 3;
Mahmoud
  • 844
  • 1
  • 10
  • 17
0

Before putting question did you go through - https://docs.angularjs.org/api/ng/directive/ngOptions

Just make below change in your controller -

$scope.selectedItem = $scope.items[0];

kunsingh
  • 254
  • 2
  • 7