angularjs – 使用ng-options和ng-selected更新模型

我正在尝试使用ng-options从下拉菜单更新模型,并使用ng-selected选择已选择的值.这是一个简化的例子(和
fiddle).

HTML

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter.id" ng-options="q.id as q.val for q in Quarters">
      <option ng-selected="Quarter.val===q.val"></option>
    </select>
    <input type="button" name="Submit" value="Submit" ng-click="submit()"/>
    <br/>
    <p>{{answer}}</p>
  </div>
</div>

function QuarterController($scope) {
    $scope.Quarters = [{val: 'Q1', id: 1}, {val: 'Q2', id:2}, {val:'Q3', id:3}, {val:'Q4', id:4}];
    $scope.Quarter = {val: 'Q2', id: 2, extraField: 'Hello'};

    $scope.submit = function() {
        $scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id + $scope.Quarter.extraField;
    };
}

那么这里发生的是下拉选项是来自$scope.Quarters的“val”,所选选项的id保存在$scope.Quarter.id中. “submit”显示来自$scope.Quarter的id和val. $scope.Quarter.id更新提交,但不是$scope.Quarter.val.谁知道怎么做到这一点?

编辑

添加了$scope.Quarter.extraField以更好地说明我正在尝试解决的问题.我需要更新id和val,但我希望extraField保持不变.

最佳答案 您的选择指令中有小错误,请参阅
here

视图:
    
      去做

  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter" ng-options="q.val for q in Quarters">
        <option value="">{{Quarter.val}}</option>
    </select>
      <input type="button" name="Submit" value="Submit" ng-click="submit()"/>
      <br/>
      <p>{{answer}}</p>

  </div>
</div>

JS:

function QuarterController($scope) {
    $scope.Quarters = [{
        val: 'Q1',
        id: 1
    }, {
        val: 'Q2',
        id: 2
    }, {
        val: 'Q3',
        id: 3
    }, {
        val: 'Q4',
        id: 4
    }];
    $scope.Quarter = {
        val: 'Q2',
        id: 2
    };

    $scope.submit = function () {
        $scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id;
    };
}
点赞