Bind ng-options value and label to ng-model

eirikir picture eirikir · Apr 22, 2015 · Viewed 22.5k times · Source

I'm using ng-options to generate a select tag whose options are locations. The labels are the location names, and the values are the location ID (in database).

I've bound the value (location ID) to an ng-model attribute, but I'd also like to bind the label (location name) to a different ng-model attribute. (I need to separate the id field since this will be POSTed to a server that expects this particular attribute.) What's the best way to do this in Angular?

My code:

<div ng-app="app"><div ng-controller="edit">
  <select ng-model="purchase.pickUpLocationId" ng-options="loc.id as loc.name for loc in purchase.availableLocations"></select>

  <!-- This is the model not yet bound: -->
  <p>You have selected {{ purchase.pickUpLocationName }}</p>

</div></div>

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

app.controller('edit', ['$scope', function($scope) {
    $scope.purchase = {
        pickUpLocationId: 30,
        availableLocations: [
            {id: 20, name: "Charleston, SC"},
            {id: 30, name: "Atlanta, GA"},
            {id: 40, name: "Richmond, VA"},
        ]
    };
}]);

Answer

scniro picture scniro · Apr 22, 2015

You can change to the following and bind to the entire object. You'll still have access to id later on for whatever you wish to do with it

<select ng-model="selected" ng-options="loc as loc.name for loc in purchase.availableLocations"></select>

<p>You have selected {{ selected.name }}</p>
<p>You havd id too! {{ selected.id }}</p>

JSFiddle Link