ng-selected不适用于ng-repeat设置默认值

时间:2016-02-09 23:08:32

标签: angularjs ng-repeat

我正在尝试设置选项的默认值 我正在使用select和ng-repeat。我在js文件中获取数据,并且我调用模型来设置值。

请查看以下代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-ngrepeat-select-production</title>


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



</head>
<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select  ng-model="datamodel">
      <option ng-repeat="dataitem in data"
                ng-selected ="{{dataitem == datamodel}}">{{dataitem}}</option>
    </select>
  </form>
  <hr>
  <tt>repeatSelect = {{datamodel}}</tt><br/>
</div>
</body>
</html>

app.js文件

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = [1,2,3,4,5];

    $scope.datamodel = 2;
 }]);
})(window.angular);

这是我的plunker

1 个答案:

答案 0 :(得分:9)

来自angular docs

  

请注意,没有ngOptions的select指令的值是   总是一个字符串。当模型需要绑定到非字符串时   值,您必须使用指令显式转换它(请参阅   示例如下)或使用ngOptions指定选项集。这是   因为选项元素只能绑定到字符串值   本。

所以将$scope.datamodel = 2;更改为$scope.datamodel = '2';有效。查看更新的plunker

但是,最好使用ngOptions代替。再次,来自文档:

  

在许多情况下,可以在<option>元素上使用ngRepeat而不是   ngOptions以实现类似的结果。但是,ngOptions提供   一些好处,例如<select>模型的灵活性   通过select作为理解表达式的一部分进行分配,和   此外,通过不创建一个减少内存和提高速度   每个重复实例的新范围。

因此,为了将模型保持为整数,您可以使用:

<select  ng-model="datamodel" ng-options="dataitem for dataitem in data">
  <option value="">Please Select</option>
</select>

请参阅plunker

相关问题