如何使用angular将对象传递给option标签中的value属性?

时间:2017-04-10 04:40:06

标签: angularjs drop-down-menu angularjs-ng-repeat

我有一个select标签,我已经通过角度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>

提交后,我获得的accessRole模型的值如下所示。

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

我希望在没有双引号的情况下传递此值。那意味着, accessRole:{“id”:1,“name”:“admin”,“accessRights”:“管理访问权限”} 我通过删除value属性中的双引号来尝试这个。(value = {{item}}) 但它没有给我解决方案。 我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

应该是这样的。

&#13;
&#13;
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);
  }
})
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用JSON.parse()将字符串转换为json对象

&#13;
&#13;
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)
}
})
&#13;
<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>
&#13;
&#13;
&#13;