Bind JSON array to SELECT dropdownlist using ng-options in AngularJS

← PrevNext →

You can populate an HTML <select> element with options using the AngularJS ng-options directive. The ng-options directive uses an array to populate the <select> element. In this article, I’ll show you how to use ng-options directive in AngularJS to dynamically bind or populate JSON array to a <select> DropDownList.

The example that I have created here, has an array of data in JSON array format, written in the controller. It has a list of employees that has joining date, employee name and their age.

What do we need?

I’ll first create my view by adding the <select> element. The directives that I need in my view are ng-model, which is required for my ng-options to work. Next, I’ll add the ng-options directive that will fill or populate the <select> element with options. Finally, I’ll add the ng-change directive (optional), which will call a function when a user selects a value from the DropDownList. (I have explained about the function, below.)

I also have an expression, which will display other details, once you select an item (in this case employee name) from the <select> list.

View and the Controller
<!DOCTYPE html>
<html>
<head>
    <title>AngularJS ng-options Example - Bind JSON Array to HTML select Element</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>

<body>
    <div ng-app="myApp" 
        ng-controller="myController">

        <select ng-model="employee"
            ng-options="emp.values.name for emp in empArray" 
            ng-change="showDetails()"
            id="emps">

            <option value="">-- Select --</option>
        </select>

        <!--SHOW OTHER DETAILS.-->
        <p style="white-space:pre-wrap;">{{details}}</p>
    </div>
</body>

<script>
    angular.module("myApp", [])
        .controller('myController', function ($scope, $filter) {

            // CREATE AN 'employees' OBJECT, WITH AN ARRAY OF DATA.
            $scope.employees = {
              "05/17/2015": { "name": "Alpha", "age": 37 },
              "03/25/2016": { "name": "Bravo", "age": 27 },
              "09/11/2015": { "name": "Charlie", "age": 29 },
              "01/07/2016": { "name": "Delta", "age": 19 },
              "03/09/2014": { "name": "Echo", "age": 32 }
            }

            $scope.empArray = Object.keys($scope.employees)
                .map(function (value, index) {
                    return { joinDate: new Date(value), values: $scope.employees[value] }
                }
            );

            // SHOW EMPLOYEE DETAILS.
            $scope.showDetails = function () {
                $scope.details =
                    'Name: ' + $scope.employee.values.name + '\n' +
                    'Age: ' + $scope.employee.values.age + '\n' +
                    'Date of Joining: ' + $filter('date')($scope.employee.joinDate, 'dd/MM/yyyy');
            };
        });
</script>
</html>
Try it

The ng-change directive, which I said is optional, will call a function (showDetails(), written in the Controller) on change that will read and display the details of the selected employee name. You do not have to worry about the <option> tag. AngularJS will take care of it. Except that, I have added a default value --Select-- to it.

👇 See this demo

with JSON array

{{details}}

I have first created an employees object using the $scope directive. The object is a JSON array, which has the joining Date, name and age of each employee.

👉 Now, you can also bind a SELECT element using dynamic data extracted from a database in AngularJS. Check out this article.
Advance AngularJS ng-options example

Next, I am converting the object to an array so I can return the data to my view. I am using Object.keys() method that provides an array of object properties. For example, add this code after you have created the employees object.

console.log(Object.keys($scope.employees));

Now, see the result in the browser’s console window. You will see an array of data (the date in our case) along with its index. The indexes are the value of each <option> of the <select> element. The label of the <option> tag however, has the name.

Object.keys() is a much faster and better alternative than using a for … next loop, to read data in a JSON array.

👉 Not just JSON file, you can extract data from XML file and populate a SELECT element in AngularJS. See this article.
XML to SELECT example in AngularJS

Finally, I have a user defined function called showDetails(). I have attached it with the $scope. When a user selects an item from the <select> list, the on change event (using the ng-change directive) will call this function. It will read the values using our model employee (see in the view section -> ng-model = "employee") and assign it to the expression named {{details}}. So you can now see all the details of the selected employee in your view.

See how I am formatting the date in the function. The date in the array is in mm-dd-yyyy format and I am converting it to dd/MM/yyyy format. You can change the date to other formats too. AngularJS date filter and its formats are very nice and simple to use.

Happy coding. 🙂

← PreviousNext →