3

Why is this repeater broken

<select name="quarter" ng-model="Quarter" ng-selected="Quarter" >
    <option ng-repeat="v in [1,2,3,4]" value="{{v}}">Q{{v}}</option>
</select>

But not the handwritten way?

<select name="quarter" ng-model="Quarter" ng-change="onQuarterChange()" ng-selected="Quarter">
    <option value="1">Q1</option>
    <option value="2">Q2</option>
    <option value="3">Q3</option>
    <option value="4">Q4</option>
</select>
BruteCode
  • 1,143
  • 7
  • 16
  • 22

2 Answers2

7

stick with ng-options

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter" ng-options="obj.value as obj.text for obj in [{'value': 1,'text' : 'Q1'},{'value':2,'text':'Q2'},{'value':3,'text':'Q3'},{'value':4,'text':'Q4'}]">
    </select>
  </div>
</div>

function QuarterController($scope) {
    $scope.Quarter = 2;
}   

http://jsfiddle.net/hDNsm/3/

you might as well define the array in your controller

Ronnie
  • 11,138
  • 21
  • 78
  • 140
  • So I need a value,text object array. hmm. Ok sure this seems to work – BruteCode Apr 02 '13 at 20:00
  • You dont need it, but if you want the text to say Q1, Q2 etc rather than 1,2.. you have to – Ronnie Apr 02 '13 at 20:06
  • Hmm. I seemed to be using `ng-selected` properly, but moving to `ng-options` fixed the selection issues. Wonder if there's a bug somewhere? – markshiz Aug 11 '16 at 22:55
4

Notice two things:

  1. 'ng-selected' directive should be written on the 'option' element and not on the 'select' element.

  2. the content of the 'ng-selected' attribute should be a condition in which the option is selected. a simple example for this could be if the value of the option equals the select model.

Your code should be something like this:

<select name="quarter" ng-model="Quarter">
    <option ng-repeat="v in [1,2,3,4]" value="{{v}}" ng-selected="v==Quarter">Q{{v}}</option>
</select>
Ofer Segev
  • 5,094
  • 2
  • 22
  • 22