ng-selected does not work with ng-repeat to set de

2019-06-17 05:23发布

问题:

I am trying to set default value of options I am using select and ng-repeat. I do get data in js file and I do call model to set value there.

Please have a look for below code :

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

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

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

Here is my plunker

回答1:

From the angular docs:

Note that the value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explicitly convert it using a directive (see example below) or use ngOptions to specify the set of options. This is because an option element can only be bound to string values at present.

So changing $scope.datamodel = 2; to $scope.datamodel = '2'; works. See updated plunker.

However, it's better to use ngOptions instead. Again, from the docs:

In many cases, ngRepeat can be used on <option> elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits, such as more flexibility in how the <select>'s model is assigned via the select as part of the comprehension expression, and additionally in reducing memory and increasing speed by not creating a new scope for each repeated instance.

So to keep your model as an integer, you can rather use:

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

See plunker