AngularJs, select directive, want to show description in dropdown list and pass to controller as code

22 Views Asked by At

AngularJS, I want to show description in select dropdown list and pass code to controller (or select code in controller and show as description in dropdown list), how to do it? I google but most is controller is array and dropdown is array also.

I try following code but fail:

In app.js

$scope.transactionTypes = [{code:'I', description:'Insert'}
,{code:'U', description:'Update'},{code:'D', description:'Delete'}];
$scope.selectedTxnType='U';

In jsp

<tr>
    <td class="control-label">Transaction Type</td> 
    <td class="input-medium"> {{selectedTxnType}} <br/>
        <select ng-model="selectedTxnType" class="span4" style="font-family: verdana;"
                ng-options="s as s.description for s in transactionTypes track by s.code">
        </select>
    </td>
</tr>

but the dropdown list cannot selected 'U'. And when I select 'I' in dropdown list, {{selectedTxnType}} shows {"code":"I","description":"Insert"} Not just 'I'.

How can I make the select dropdown to select the item by its 'code'? and when select an item in dropdown, pass the 'code' to controller?

1

There are 1 best solutions below

0
Naren Murali On BEST ANSWER

You can do this without using ng-options, because when you do with it, we need to supply an object { code: 'I', description: 'Insert' } only then it will work.


instead you can use ng-repeat with options and ng-value set to item.code, this will generate the expected result!

function LoginController($scope) {
  $scope.transactionTypes = [{
    code: 'I',
    description: 'Insert'
  }, {
    code: 'U',
    description: 'Update'
  }, {
    code: 'D',
    description: 'Delete'
  }];
  $scope.selectedTxnType = 'U';
}

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

app.controller('LoginController', ['$scope', LoginController])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
<div ng-app="angularTest" ng-controller="LoginController">
  <tr>
    <td class="control-label">Transaction Type</td>
    <td class="input-medium"> {{selectedTxnType}} <br />
      <select ng-model="selectedTxnType" class="span4" style="font-family: verdana;">
          <option ng-repeat='item in transactionTypes track by item.code'
                  ng-value='item.code' ng-bind='item.description'></option>
      </select>
    </td>
  </tr>
</div>