使用ng-selected和ng-repeat AngularJS的奇怪行为

时间:2016-01-03 07:49:39

标签: angularjs

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

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-static-select-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
  <script src="app.js"></script>



</head>

<body ng-app="staticSelect">

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

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

</body>

</html>

ng-selected似乎只选择最后一个元素。这是为什么?

我检查了元素,ng-selected标记为true。但是,如果它不是最后一个元素,则最初不会被选中。

1 个答案:

答案 0 :(得分:1)

你可以试试这段代码,

Automatic

在您的控制器中,您必须指定&#34; Quarter&#34;,如:

<select name="quarter" ng-model="Quarter" ng-options="item as 'Q'+item  for item in [1,2,4,3]">

以下是一个完整的例子:

&#13;
&#13;
$scope.Quarter = 3
&#13;
(function(angular) {
  'use strict';
angular.module('staticSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     singleSelect: null,
     multipleSelect: [],
     option1: 'option-1',
    };

    $scope.Quarter = 3;
    
    $scope.forceUnknownOption = function() {
      $scope.data.singleSelect = 'nonsense';
    };
 }]);
})(window.angular);
  
&#13;
&#13;
&#13;