The Ng-Options in AngularJS

Rana Hasnain Khan Mar 05, 2022
The Ng-Options in AngularJS

This tutorial will discuss the ng-options and how we can use it to display options in select using AngularJS.

Use ng-options in AngularJS

The ng-options is used to build and bind HTML elements with options to a model property. We use ng-options to specify options in a select list.

ng-options is specifically designed to populate the items of a dropdown list. We will go through an example in which we will create a dropdown that will use ng-options to populate the options.

First of all, we add the AngularJS library and app.js file using script tags.

# AngularJS
<head>
    <script src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
    <script src="app.js"></script>
  </head>

Define AngularJS application using ng-app and controller using ng-controller.

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

Now, in app.js, we will create our module.

# AngularJS
var app = angular.module('myApp', []);

We will create a controller which will define an array, selectedItem, and add assigned values to the array for options in app.js.

# AngularJS
app.controller('myController', function($scope) {

  $scope.lists = [];
  $scope.selectedItem = { name: 'second', id: 5 };
  $scope.lists = [{name: 'first', id: 3 },{ name: 'second', id: 5 },{ name: 'third', id: 7 }];

});

Lastly, we will create a frontend for our application.

# AngularJS
    <p>selected item is : {{selectedItem}}</p>
    <p> name of selected item is : {{selectedItem.name}} </p>
    <select ng-model="selectedItem" ng-options="list.name for list in lists track by list.id"></select>

Output:

ng-options example in angularjs

In the above example that using ng-options, it is very easy to display a list of options in select. We don’t need to write any additional lines of code to make an item selected when a user selects an item.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn