Tpk43
Tpk43

Reputation: 331

Bind array values to dropdown in AngularJs

I have an Edit Page there I have an drop down called Role, while inserting I sent a value (like 1 instead "Role Name") to db, while retrieving to edit page I couldn't able to initialize the selected text in drop down

below is my html code

<label class="adjust1-label-right">Role</label>
<select id="role" class="adjust-select-combo" ng-options="r.role_name for r in Role_Name track by r.roleid" ng-model="role">
      <option ng-repeat="rol.roleid for rol in Role_Name" value="{{rol.roleid}}">{{rol.role_name}}</option>
</select>

I tried this but no luck

$scope.role = $scope.Role_Name[0];

My data looks like

[{"Role_Id":1,"User_Id":10001}]

Upvotes: 1

Views: 1736

Answers (2)

cнŝdk
cнŝdk

Reputation: 32175

Your binding won't work, because you are using ng-options in your select along with ng-repeat in your options, only one of them should be used.

And use ng-value instead of value, this is how should be your HTML binding:

<select id="role" class="adjust-select-combo" ng-model="role">
   <option ng-selected="rol == role" 
        ng-repeat="rol in Role_Name" 
        ng-value="rol.Role_Id">{{rol.User_Id}}
   </option>
</select>

Demo:

This is a working Snippet:

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

app.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.Role_Name = [{
    "Role_Id": 1,
    "User_Id": 10001
  }, {
    "Role_Id": 2,
    "User_Id": 10002
  }, {
    "Role_Id": 3,
    "User_Id": 10003
  }];
  $scope.role = $scope.Role_Name[1];

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>


<html ng-app="app">

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>

<body>

  <div ng-controller="MainCtrl">
    <select id="role" class="adjust-select-combo" ng-model="role">
   <option ng-selected="rol == role" 
        ng-repeat="rol in Role_Name" 
        ng-value="rol.Role_Id">{{rol.User_Id}}
   </option>
</select>
  </div>

</body>

</html>

Upvotes: 3

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16856

Have you tried with just using the ng-options

<select id="role" 
        class="adjust-select-combo" 
        ng-options="r.Role_Id as r.User_Id for r in Role_Name" 
        ng-model="role"></select>

To set the selected role

$scope.role = $scope.Role_Name[0].Role_Id;

Upvotes: 0

Related Questions