spcd
spcd

Reputation: 1

How to pass an object to the value property in option tag using angular?

I have a select tag which i have loaded the data through angular ng-repeat.

  <select ng-model="user.accessRole">
     <option ng-selected="{{item.name == user.accessRole.name}}"
      ng-repeat="item in accessRoles" value="{{item}}">
         {{item.name}}
     </option>
  </select>

Once I submit this the value I got for accessRole model is as below.

accessRole:"{"id":1,"name":"admin","accessRights":"administrative access"}"

I want this value to be passed without double quotes. That means, accessRole:{"id":1,"name":"admin","accessRights":"administrative access"} I tried out this by removing double quotes in value property.(value={{item}}) But it didn't give me the solution. How can i do this?

Upvotes: 0

Views: 853

Answers (2)

Hadi
Hadi

Reputation: 17299

It should be like to this.

var app = angular.module('anApp', []);
app.controller('ctrl', function($scope) {

  $scope.user = {};
  $scope.accessRoles= [{"id":1,"name":"admin","accessRights":"administrative access"}];
  
  $scope.display = function(){
    console.log($scope.user);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>

<div ng-app="anApp" ng-controller="ctrl">
  <div class="form-group">
    <select ng-options="role as role.name for role in accessRoles" ng-model="user.accessRole" ng-change="display()">
    </select>
  </div>
</div>

Upvotes: 2

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

use JSON.parse() to convert string to json object

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.user = {};
$scope.accessRoles= [{"id":1,"name":"admin","accessRights":"administrative access"}]


$scope.submit = function(){
 console.log($scope.user)
  $scope.user.accessRole = JSON.parse( $scope.user.accessRole)
 console.log($scope.user)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <select ng-model="user.accessRole">
     <option  ng-repeat="item in accessRoles" value="{{item}}">
         {{item.name}}
     </option>
  </select>
  <button ng-click="submit()">click</button>
</div>

Upvotes: 0

Related Questions