Sonil Gandhi
Sonil Gandhi

Reputation: 179

how to display option as selected in select box in angularjs?

I can't set option selected in angularjs

<tr ng-repeat="leader in filtered = (list | orderBy:sort.active:sort.descending) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
    <td>
       <select class="form-control mt10" name="leaderRole" ng-model="leader.role_id" ng-class="{ inputerror: !leader.role_id}">
          <option value="">Please select role</option>
          <option ng-repeat="role in employeeRole" ng-selected="{{leader.role_id == role.id}}" value="{{role.id}}">{{role.description}}</option>
       </select>
    </td>
</tr>

Controller Part

var leaders_list = angular.module('leaders_list'); //getter
leaders_list.controller('LeaderController',['$scope','$http','$filter',LeaderController]);
function LeaderController($scope,$http,$filter)
{
   $scope.list = [
      {
        "title": "XYZ",
        "name_first": "ABC",
        "name_last": "EFG",
        "email": "[email protected]",
        "id": 1,
        "role_id": 3
      }
   ];

  $scope.employeeRole = [
    {
      "id": 2,
      "description": "JKL",
      "is_active": true
    },
    {
      "id": 3,
      "description": "STV",
      "is_active": true
    }
  ];
}

Here leader.role_id is value of role_id for each leader, when i'm doing above code it did not show my value as selected.

If I remove ng-model from select box it will show my value as selected.

Plunker Link: https://plnkr.co/edit/qesu3J6mxJdS6bTjPXKI?p=info

can anyone suggest me how to do this ?

Upvotes: 0

Views: 1183

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

You make your own life difficult by not using ng-options as recommended.

Just replace your select with

<select class="form-control mt10" name="leaderRole" 
        ng-model="leader.role_id" ng-class="{ inputerror: !leader.role_id}"
        ng-options="role.id as role.description for role in employeeRole">
  <option value="">Please select role</option>
</select>

https://plnkr.co/edit/fW9O6BCDOl59aziTz7zX?p=preview

Upvotes: 1

Related Questions