AngularJS lets you create dropdown lists based on items in an array, or an object.
If you want to create a dropdown list, based on an object or an array in AngularJS, you should use the ng-options
directive:
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.
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" } ]; });
ng-value
insead of value:ng-options
directive to create dropdown lists, the selected value can be 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: