1

My HTML looks like this

<select ng-options="possibleConflict.id as possibleConflict.value for possibleConflict in possibleConflicts" ng-model="key"></select>

and the controller looks like this

app.controller('MainCtrl', function($scope) {
  $scope.key = 2; // Note This value can change 
  $scope.possibleConflicts = [{
      id: '1',
      value: 'red'
    }, {
      id: '2',
      value: 'blue'
    }]
}

Here is a working Plunker example

Why isn't "red" selected as default when the page loads ? and how can I get it to be set as default ?

I have looked at this and this thread, but couldn't find a solution

Community
  • 1
  • 1
LegionDev
  • 1,391
  • 4
  • 15
  • 29

4 Answers4

1

Just set $scope.key = "1"; It should do the trick. It has to be a string value since that is what you defined in your array.

Baltic
  • 56
  • 3
  • Doesn't work, you can test it in the plunker example – LegionDev Feb 08 '17 at 15:40
  • I believe it does. Working plunker https://plnkr.co/edit/C2LdF3NSLPzT7ytT86Ip?p=preview – Baltic Feb 08 '17 at 15:42
  • Ok I see it works, I dumbed down the code down to put in plunker to test, it seems the type does matter, I thought angular would automatically cast it to the correct type – LegionDev Feb 08 '17 at 15:45
0

Try by just changing your key variable to:

$scope.key = $scope.possibleConflicts[1].id;

Or changing both template and key variable:

<select ng-options="possibleConflict  as possibleConflict.value for possibleConflict in possibleConflicts" ng-model="key"></select>

together with

$scope.key = $scope.possibleConflicts[1];
LegionDev
  • 1,391
  • 4
  • 15
  • 29
Dario
  • 6,152
  • 9
  • 39
  • 50
0

you should set the default value as a string: '2'

$scope.def = '2';

and the 'blue' is selected.

jeremy
  • 43
  • 6
0

Working demo :

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    $scope.possibleConflicts = [{
      id: '1',
      value: 'red'
    }, {
      id: '2',
      value: 'blue'
    }];
    $scope.key = $scope.possibleConflicts[0].id; // Note This value can change
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select ng-options="possibleConflict.id as possibleConflict.value for possibleConflict in possibleConflicts" ng-model="key"></select>
</div>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123