ng-options with simple and complex array angularjs

In this article am going to explain how to use ng-options with simple and complex(array of objects) arrays

Assume you have following array

$scope.fruits = ['apple', 'banana', 'orange'];

If you want to show them in a dropdown using ng-options use the following code

<select name="fruit" data-ng-model="selectedFruit"  data-ng-options="fruit as fruit for fruit in fruits"></select>

What you get in the resulting html is below

<option label="apple" value="string:apple">apple</option>
<option label="banana" value="string:banana">banana</option>
<option label="orange" value="string:orange">orange</option>

when you select any option the value gets selected is same as value shown in dropdown.

Use ng-options for array of objects:


If you have an array of objects like below

$scope.fruits = [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'orange' }];

Use the following html to show them in dropdown

<select name="fruit" data-ng-model="selectedFruit"  data-ng-options="fruit.id as fruit.name for fruit in fruits"></select>

If you use the above html then in the dropdown it shows name of the fruit but internally it stores the id of the fruit when you select any value from dropdown. resulting html code looks like below

<option label="apple" value="number:1">apple</option>
<option label="banana" value="number:2">banana</option>
<option label="orange" value="number:3">orange</option>

When you click on dropdown it shows names of the fruits but when you select any option internally id of the object will be selected.

Check this Plunker for working example: ng-options with simple and complex arrays

This is how ng-options works with simple and complex arrays.

For more posts on angularjs visit: AngularJS

No comments:

Post a Comment