为什么ng-selected不适用于ng-repeat?

时间:2013-04-02 19:28:17

标签: angularjs

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>

2 个答案:

答案 0 :(得分:7)

坚持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/

您也可以在控制器中定义数组

答案 1 :(得分:4)

注意两件事:

  1. 'ng-selected'指令应该写在'option'元素上而不是'select'元素上。

  2. 'ng-selected'属性的内容应该是选择该选项的条件。一个简单的例子就是如果选项的值等于选择模型。

  3. 您的代码应该是这样的:

    <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>