Ng-selected does not work with ng-repeat to set default

I am trying to set the default value for the parameters. I am using select and ng-repeat. I get the data in a js file and I call the model to set the value there.

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

+7
angularjs ng-repeat
source share
1 answer

From angular docs :

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

This is how the work of $scope.datamodel = 2; up to $scope.datamodel = '2'; . See Updated plunker .

However, it is better to use ngOptions . Again, from the docs:

In many cases, ngRepeat can be used for <option> elements instead of ngOptions to achieve a similar result. However, ngOptions provides some advantages, such as greater flexibility in how the <select> model is assigned through select as part of an understanding expression, and further reducing memory and increasing speed without creating a new area for each repeating instance.

So, so that your model is an integer, you can use:

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

See plunker

+9
source share

All Articles