How to bind data to Select tag using AngularJS ng-options?

How to bind data to Select tag using AngularJS ng-options?

While Developing a Web App, its a very common behavior to display list of values in a Select tag. Let’s discuss about an Employee Management System where many times we required to display employee names in a dropdownlist. Assume we have a JSON file which contains employee details & the application architecture is with AngularJS. Look at the below example here I am binding JSON formatted data from scope object using AngularJS ng-options.

To show list of employee names here I added for loop inside ng-options “emp.name for emp in empDetails”. Here empDetails is the object which holds JSON formatted data. Due to security reason outside the scope we can’t modify scope data directly. The reason I am cloning empDetails data to emp object inside ng-options. Then using embedded for loop binding emp.name.

Using AngularJS ng-options

<!DOCTYPE html>
<html ng-app="EmployeeMod">
<head>
<title>How to bind data to Select Control using ng-options?</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script type="text/javascript">
/*Declaring the Module*/
var EmployeeMod = angular.module('EmployeeMod', []);
EmployeeMod.controller('EmployeeCtrl', function ($scope) {
/*Declaring JSON formatted Data*/
$scope.empDetails = [
{name:'Rupak Roy', designation:'Assistant Manager'},
{name:'Sujata Malhotra', designation:'Project Manager', notAnOption: true},
{name:'Raghav Setthy', designation:'Team Leader'},
{name:'Mohini Sharma', designation:'Graphics Designer', notAnOption: true},
{name:'Sanjarekha Dash', designation:'Software Engineer', notAnOption: false}
];
});
</script>
</head>
<body ng-controller="EmployeeCtrl">
<!--Binding Data using ng-options-->
<select ng-model="empName" ng-options="emp.name for emp in empDetails"></select>
</body>
</html>