使用角度选择框获取所选值(整个对象)

时间:2015-07-23 08:12:16

标签: angularjs

我可以使用以下JSON渲染角度选择框。

$scope.rejectionTypes = [  
   {  
      "code":"88",
      "description":"Other reasons",
      "type":{  
         "code":"PR",
         "description":"Permoanent Rejection"
      }
   },
   {  
      "code":"92",
      "description":"Bank Excluded",
      "type":{  
         "code":"OT",
         "description":"Non Financial Transactions"
      }
   }
]

模板

<select class="form-control" name="tranCode" data-ng-model="rowUnderEdit.rejectionReason" data-ng-change="populateRejectDesc(transactionType)">
    <option data-ng-repeat="transactionType in rejectionTypes" ng-selected="compareSelect(transactionType, rowUnderEdit.rejectionReason)" >{{transactionType.code}}-{{transactionType.description}}</option>
</select>

问题是,每当选项更改需要从'transactionType'获取整个对象(即代码,描述和类型)。有没有办法获得整个对象。

{  
          "code":"88",
          "description":"Other reasons",
          "type":{  
             "code":"PR",
             "description":"Permoanent Rejection"
          }
       }

我尝试以下列方式获取它,但它是抛出:' transactionType未定义'

data-ng-change="populateRejectDesc(transactionType)"

enter image description here

2 个答案:

答案 0 :(得分:0)

<select>旨在与ng-options一起使用 准备对象中的label

$scope.rejectionTypes.map(function(item){
  item.label = item.code + '-' + item.description;
});

并像这样显示它们

<select ng-options="item as item.label for item in rejectionTypes" ng-model="selected">

提供给selected的变量ng-model将控制所选项目。你可以在控制器($scope.selected = $scope.rejectionTypes[0])中分配它,并在用户界面改变后读取它的值
Plunker

答案 1 :(得分:0)

你想要的是同样的事情,我是在ng-options的帮助下进行的,因为当你使用ng-repeat和<option>时,<select>的ng-model将包含&#39; string&# 39;值。

HTML:

<div ng-app='myApp' ng-controller='myCtrl'>
<select class="form-control" name="tranCode" data-ng-model="rowUnderEdit.rejectionReason" data-ng-change="populateRejectDesc(rowUnderEdit.rejectionReason)" data-ng-options="check(transactionType) for transactionType in rejectionTypes">

</select>
</div>

Angularjs:

var app= angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
    $scope.rejectionTypes = [  
   {  
      "code":"88",
      "description":"Other reasons",
      "type":{  
         "code":"PR",
         "description":"Permoanent Rejection"
      }
   },
   {  
      "code":"92",
      "description":"Bank Excluded",
      "type":{  
         "code":"OT",
         "description":"Non Financial Transactions"
      }
   }
];
    $scope.compareSelect=function(transactionType, rejectionReason){
       // $scope.selectedObject=transactionType;
        console.log(rejectionReason);
    };
    $scope.populateRejectDesc=function(transactionType){
        console.log('Object',transactionType);//your object
    }
    $scope.check=function(object){
      return object.code+'-'+object.description;
    }
});

小提琴解决方案:http://jsfiddle.net/y4dy1uqu/4/