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"},
]
};
}]);
ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable. Save this answer.
Use ng-init to set default value for ng-options .
ng-repeat creates a new scope for each iteration so will not perform as well as ng-options. For small lists, it will not matter, but larger lists should use ng-options. Apart from that, It provides lot of flexibility in specifying iterator and offers performance benefits over ng-repeat.
The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.
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>
My suggestion is to model as a hash first
{
"20": "Charleston, SC",
"30": "Atlanta, GA"
}
and then use {{availableLocations[purchase.pickUpLocationId]}}
and make ng-options as
<select ng-model="purchase.pickUpLocationId" ng-options="id as label for (id, label) in purchase.availableLocations"></select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With