Search code examples
javascriptangularjsdrop-down-menung-options

Pre-select option form ng-options list


I'm trying to preselect a item in the list which is generated by ng-options directive. Could someone please tell me whats happening in the plunker?

http://plnkr.co/edit/GTnR76HEnB5NxQRe484m?p=preview

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
  <script>
    function MyCntrl($scope) {
      $scope.prop = {
        "type": "select",
        "name": "Service",
        "values": [{
          'name': "Service 1"
        }, {
          'name': "Service 2"
        }, {
          'name': "Service 3"
        }, {
          'name': "Service 4"
        }]
      };
      $scope.selected1 = $scope.prop.values[1]
      $scope.selected2 = {
        "name": "Service 2"
      }

    }
  </script>
</head>

<body>

  <div ng-controller="MyCntrl">
    Works <br>
  <select ng-model="selected1" ng-options="v.name for v in prop.values">
    </select> {{selected1}} <br>
    Does not work. Why? <br>
    <select ng-model="selected2" ng-options="v.name  for v in prop.values">
    </select>
    {{selected2}}
  </div>
</body>
</html>

Solution

  • Bijay Rai's statement is correct but not full answer.

    ngOption has rather complicated expressions and you should bother to examine documentation. If you change the way the option's object is being tracked you can avoid using same object by reference as stated. For example, use select as pattern

    <select ng-model="selected2" ng-options="v.id as v.name for v in prop.values">
    </select>
    

    Then you can simply assign selected like this:

      $scope.selected2 = 3;
    

    Updated plunkr