Search code examples
javascriptangularjsangularjs-ng-repeatangular-ngmodel

How to store selected value in ng-model if source list is array of objects?


I have array of objects like:

vm.items = [{id: "1", val: "a"},{id: "2", val: "b"},{id: "3", val: "c"}]

And I bound it to select option like:

<select ng-model="vm.model.id" >
    <option value="">select somthing</option>
    <option ng-repeat="i in vm.items" value="{{i.id}}">{{i.val}}</option>
</select>

But when I select some item from dropdown I get whole object {} and I want only id. How can I do that?


Solution

  • You can use the ng-options directly on the select tag. If your json contains an id and name variable you can specify it as this:

    <select ng-model="vm.model.id" ng-options="i.id as i.name for i in vm.items">
        <option value="">select somthing</option>
    </select>
    

    The i.id is set to the options value and the i.name is set to the text