6

I'm trying to set ng-selected in my option element, selected attribute is set to true, but option not selected, When I remove ng-model from select all become working.

The question: How to make option selected, when I'm using the model?

Here is my plunker (selected not working here)

My code:

var app = angular.module("plunker", []);

app.controller("TestController", ["$scope", function($scope) {
  $scope.test = 1;
  $scope.array = [
        {"id": 1, "name": "first"}, 
        {"id": 2, "name": "second"}, 
        {"id": 3, "name": "third"}
      ];
}]);

My template:

  <body ng-controller="TestController">
    Selected item must be {{ array[test-1].name }}
    <select ng-model="myModel">
      <option value="">Choose item..</option>
      <option ng-repeat="item in array" 
              ng-value="item.id" 
              ng-selected="item.id == test">
        {{ item.name }} ({{item.id == test}})
      </option>
    </select>
  </body>

Thanks a lot for any help!

Venkat.R
  • 7,420
  • 5
  • 42
  • 63
Sergio Ivanuzzo
  • 1,820
  • 4
  • 29
  • 59
  • 1
    ng-selected and ng-model exclude one another. Your model should match the option id – Raulucco Jan 25 '16 at 15:59
  • 1
    for select i think you need ng-options https://docs.angularjs.org/api/ng/directive/ngOptions – Pablo Ortuño Jan 25 '16 at 16:04
  • once ng-model removed from select. its picking the value to be selected. look at this forked one - http://plnkr.co/edit/u5bYQo7IgNmiABDZSyIQ?p=preview – Venkat.R Jan 25 '16 at 16:06

2 Answers2

7

Don't use ngSelected with ngRepeat. Go with ngOptions:

  <body ng-controller="TestController">
    Selected item must be {{ array[test-1].name }}
    <select ng-model="myModel" ng-options="item.id as item.name for item in array">
      <option value="">Choose item..</option>
    </select>
  </body>
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • I was about to write this! :P i think this is the correct answer!! – Pablo Ortuño Jan 25 '16 at 16:05
  • but what if i have to keep selected value based on ng-repeat value? check this https://stackoverflow.com/questions/50305993/how-to-use-select-inside-ng-repeat-and-keep-value-selected-on-api-call-data?noredirect=1#comment87628318_50305993 – Sudarshan Kalebere May 12 '18 at 14:46
2

Don't use ngSelected with ngModel

From the Docs:

Note: ngSelected does not interact with the <select> and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the select, you should not use ngSelected on the options, as ngModel will set the select value and selected options.

— AngularJS ng-selected API Reference

See additional Docs:

See Stackoverflow:

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95