Online Snippets Library

Create dropdown by ng-repeat and ng-options in AngularJS

We can create dropdown in angular js by ng-repeat or ng-options directive.

ng-repeat

AngularJS ng-repeat directive is used to repeats an HTML element

Example

HTML
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<div ng-app="myfirstApp" ng-controller="dropdownController">
<p>First dropdown selected item is : {{selectedItem}}</p>
<select ng-model="selectedItem">
<option value="">--Select--</option>
<option ng-repeat="item in items" value="{{item.age}}">{{item.name}}</option>
</select>
</div>
</body>
</html>
JavaScript
   var app = angular.module('myfirstApp', []);
    app.controller('dropdownController', function($scope) {
        $scope.items = [{
            name: 'max',
            age: 26
        }, {
            name: 'manish',
            age: 25
        }, {
            name: 'pawan',
            age: 30
        }];
        });

ngOptions

AngularJS ngOptions attribute can be used to generate a list of <option> elements for the <select> element using the array or object.

HTML
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<p>Second dropdown selected item is : {{student.currentActivityId}}</p>
<select ng-model="student.currentActivityId" data-ng-options="a.id as a.name group by a.classname for a in myclass">
</select>
</body>
</html>
JavaScript
   var app = angular.module('myfirstApp', []);
    $scope.student = {
            name: "Dani",
            currentActivityId: 3
        };

        $scope.myclass = [{
            id: 1,
            classname: "Grade1",
            name: "Max Joe"
        }, {
            id: 2,
            classname: "Grade1",
            name: "Samm"
        }, {
            id: 3,
            classname: "Grade2",
            name: "Dani"
        }, {
            id: 4,
       classname: "Grade3",
        name: "yo yo singh"
        }];
         });