Search code examples
javascriptangularjsdictionaryselectng-options

ng-options pass value from dictionary


I have a dictionary, so in json

Object {1: "value1", 4: "value2" }

And I would like to pass selected value instead of key.

Now I code like this:

<select ng-model="myModel.myValue" ng-options="key as item for (key, value) in items" class="form-control">
<option value="">Choose</option>                                          </select>

Solution

  • use this ng-options="value as value for (key, value) in items". it will assign value instead of key to ng-model

    angular.module("app",[])
    .controller("ctrl",function($scope){
    	$scope.items = {1: "value1", 4: "value2" };
      $scope.myModel = {}
    })
    <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="myModel.myValue" ng-options="value as value for (key, value) in items" class="form-control">
    <option value="">Choose</option>                                          </select>
    {{myModel.myValue}}
    </div>