AngularJS Select Boxes


AngularJS lets you create dropdown lists based on items in an array, or an object.


Creating a Select Box Using ng-options

If you want to create a dropdown list, based on an object or an array in AngularJS, you should use the ng-options directive:

Output :



ng-options vs ng-repeat

You can also use the ng-repeat directive to make the same dropdown list:

Because the ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list. However, the ng-options directive was made especially for filling a dropdown list with options.

What Do I Use?

You can use both the ng-repeat directive and the ng-options directive.

Assume you have an array of objects:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.students = [
    { id: 1, name: "Angular" },
    { id: 2, name: "Asp.net" },
    { id: 3, name: "Core Java" }
  ];
});
Output :



When using the value as an object, use ng-value insead of value:
Output :



When you use the ng-options directive to create dropdown lists, the selected value can be an object.
In this example you can display both the model and the color of the selected element.

Output :

The Data Source as an Object

In the previous examples the data source was an array, but we can also use an object.

Assume you have an object with key-value pairs:

    
      $scope.cars = {
  car01 : "Ford",
  car02 : "Fiat",
  car03 : "Volvo"
};
    
  

The expression in the ng-options attribute is a bit different for objects:

The selected value will always be the value in a key-value pair. The value in a key-value pair can also be an object:

Output :