MOCKSTACKS
EN
Questions And Answers

More Tutorials









Angular ngOptions


ngOptions is a directive that simplifies the creation of a html dropdown box for the selection of an item from an array that will be stored in a model. The ngOptions attribute is used to dynamically generate a list of < option > elements for the < select > element using the array or object obtained by evaluating the ngOptions comprehension expression.

With ng-options the markup can be reduced to just a select tag and the directive will create the same select:

<select ng-model="selectedFruitNgOptions"
 ng-options="curFruit as curFruit.label for curFruit in fruit">
</select>


There is anther way of creating SELECT options using ng-repeat, but it is not recommended to use ng-repeat as it is mostly used for general purpose like, the forEach just to loop. Whereas ng-options is specifically for creating SELECT tag options.

Above example using ng-repeat would be

<select ng-model="selectedFruit">
 <option ng-repeat="curFruit in fruit" value="{{curFruit}}">
 {{curFruit.label}}
 </option>
</select>

Lets see the above example in detail also with some variations in it.

Data model for the example:

$scope.fruit = [
 { label: "Apples", value: 4, id: 2 },
 { label: "Oranges", value: 2, id: 1 },
 { label: "Limes", value: 4, id: 4 },
 { label: "Lemons", value: 5, id: 3 }
];

<!-- label for value in array -->

<select ng-options="f.label for f in fruit" ng-model="selectedFruit"></select>


Option tag generated on selection:

<option value="{ label: "Apples", value: 4, id: 2 }"> Apples </option>


Effects:

f.label will be the label of the < option > and the value will contain the entire object.


Conclusion

In this page (written and validated by ) you learned about AngularJS ngOptions . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS ngSrc.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.