Zanko
Zanko

Reputation: 4694

Strange behavior with ng-selected and ng-repeat 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 seems to be only selecting the last element. Why is this?

I have inspected the element and the ng-selected tag is true. However, if it is not the last element then it won't be selected initially.

Upvotes: 1

Views: 49

Answers (1)

Abed Alzain
Abed Alzain

Reputation: 759

you can try this code,

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

in your controller you have to specify "Quarter", like :

$scope.Quarter = 3

Here is a full example:

(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);
  
<!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>
 
</head>

<body ng-app="staticSelect" ng-controller="ExampleController">

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

Upvotes: 1

Related Questions