Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

ng-options vs ng-repeat

You can also use the ng-repeat directive to create the same dropdown list.

Example

<select>
  <option ng-repeat=”x in names”>{{x}}</option>
</select>

Since the ng-repeat directive repeats a block of HTML for each item in an array, it can be used to generate options in a dropdown list. However, the ng-options directive is specifically designed for populating a dropdown list with options.

What Do I Use?

You can use both the ng-repeat and ng-options directives with an array of objects.

$scope.cars = [
  {model : “Ford Mustang”, color : “red”},
  {model : “Fiat 500”, color : “white”},
  {model : “Volvo XC90”, color : “black”}
];

Example

Using ng-repeat:

<select ng-model=”selectedCar”>
  <option ng-repeat=”x in cars” value=”{{x.model}}>{{x.model}}</option>
</select>

<h1>You selected: {{selectedCar}}</h1>

When using the value as an object, utilize ng-value instead of value.

Example

Using ng-repeat with an object:

<select ng-model=”selectedCar”>
  <option ng-repeat=”x in cars” ng-value=”{{x}}>{{x.model}}</option>
</select>

<h1>You selected a {{selectedCar.color}} {{selectedCar.model}}</h1>

Example

Utilizing ng-options:

<select ng-model=”selectedCar” ng-options=”x.model for x in cars”>
</select>

<h1>You selected: {{selectedCar.model}}</h1>
<p>Its color is: {{selectedCar.color}}</p>

When the selected value is an object, it can contain additional information, making your application more flexible.