How to work with the Bootstrap DropDown in AngularJS


In this post we will learn how to work with the Bootstrap dropdown in an AngularJS APP. In a step by step by approach, we’ll cover how to:

1.       Bind a dropdown with the controller;

2.       Select an item in the drop down and pass to controller;

3.       Bind a dropdown with the Web API

 

Bootstrap dropdown

A simple bootstrap dropdown button can be created as shown in the listing below:

<div class="dropdown">

        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

            Subject

            <span class="caret">span>

        button>

        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

            <li><a href="#">Physicsa>li>

            <li><a href="#">Matha>li>

            <li><a href="#">Chemistrya>li>

            <li><a href="#">Hindia>li>

        ul>

    div>

 

In the dropdown we’ve created above, we will be navigated to another view or page on selecting an item and all the items are hard coded in the dropdown.

 

Bootstrap dropdown with AngularJS controller data

Now let us assume that we need to create a bootstrap dropdown in the AngularJS application. To create that, first we need to make sure that the reference of bootstrap CSS is added in the project, as shown in the listing below:

 

   <link href="../Content/bootstrap.css" rel="stylesheet" />

    <script src="../Scripts/angular.js">script>

    <script src="../Scripts/angular-route.js">script>

    <script src="home.js">script>

 

 

Next let us create AngularJS controller. In the controller there is an array called subjects which will be bound to the bootstrap dropdown. The controller can be created as shown in the listing below:

MyApp.controller('SubjectDropDownController', function ($scope) {

 

    $scope.subjects = ['Math', 'Physics', 'Chemistry', 'Hindi', 'English'];

});

 

We can bind the subjects array to create a dropdown as shown in the listing below:

<div ng-controller="SubjectDropDownController">

    <div class="dropdown">

        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

            Subject

            <span class="caret">span>

        button>

        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

            <li ng-repeat="a in subjects"><a href="#">{{a}}a>li>

        ul>

    div>

div>

 

Here we’re doing the following tasks to bind the array from the AngularJS controller in the bootstrap dropdown:

1.       Setting the ng-controller value to the SubjectDropDownController

2.       Using the ng-repeat directive on li element to repeat the elements from the array

In the above dropdown, all the items are links which we will navigate to by clicking them. To invoke a controller function on the dropdown item click, we need to use the ng-click directive as shown in the listing below:

 

<div ng-controller="SubjectDropDownController">

    <div class="dropdown">

        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

            Subject

            <span class="caret">span>

        button>

        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

            <li ng-repeat="a in subjects"><a ng-click="dropboxitemselected()">{{a}}a>li>

        ul>

    div>

div>

 

In the controller we need to create a function as shown in the listing below:

MyApp.controller('SubjectDropDownController', function ($scope) {

 

    $scope.subjects = ['Math', 'Physics', 'Chemistry', 'Hindi', 'English'];

 

    $scope.dropboxitemselected = function () {

        alert("drop box item selected");

    }

});

 

 

Selecting an Item in the Dropdown

One common requirement in the dropdown would be to select an item. There might be other ways of doing it, but I prefer to do it in a simple way as discussed in the following steps:

1.       Create a variable on the $scope in the controller. Let us say the variable name is selecteditem

2.       On the ng-click directive, call a function and pass the item in the function

3.       Assign the item which is passed as parameter in the function to the selecteditem variable

4.       Data bind the dropdown display item to the selecteditem variable

 

The controller can be modified as shown in the listing below:

MyApp.controller('SubjectDropDownController', function ($scope) {

 

    $scope.subjects = ['Math', 'Physics', 'Chemistry', 'Hindi', 'English'];

    $scope.selectedItem;

    $scope.dropboxitemselected = function (item) {

 

        $scope.selectedItem = item;

        alert($scope.selectedItem);

    }

});

 

And the drop down can be modified to bind the selected item as shown in the listing below:

 

<div ng-controller="SubjectDropDownController">

    <div class="dropdown">

        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

            {{selectedItem}}

            <span class="caret">span>

        button>

        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

            <li ng-repeat="a in subjects"><a ng-click="dropboxitemselected(a)">{{a}}a>li>

        ul>

    div>

div>

 

 

Getting data from the web API

In real time applications, we may have to bring data from the database and bind to the UI. There are various ways to expose data from the database. One of the most popular approach is writing the Web API.  If required, you may want to read A Step-by-Step Guide to Working with the ASP.NET Web API and AngularJS.

Now let’s say we have created the Web API, and in the AngularJS application we need to create a service to work with the Web API. This can be created as shown in the listing below:

 

MyApp.factory('TeacherService', ['$http', function ($http) {

    var urlBase = 'http://localhost:25221/api';

    var TeacherService = {};

    TeacherService.getSubjects = function () {

        return $http.get(urlBase + '/Subjects');

    };

}]);

 

Next, in the controller we need to use the AngularJS service to fetch the data from the Web API.  We passed TeacherService as the dependency and then called getSubjects() function of the service to fetch the data from the Web API.

 

MyApp.controller('SubjectDropDownController', function ($scope, TeacherService) {

 

    //$scope.subjects = ['Math', 'Physics', 'Chemistry', 'Hindi', 'English'];

    $scope.subjects;

    $scope.selectedItem;

    $scope.dropboxitemselected = function (item) {

 

        $scope.selectedItem = item;

        alert($scope.selectedItem);

    }

 

    getSubjects();

    function getSubjects() {

        TeacherService.getSubjects()

            .success(function (subjects) {

                $scope.subjects = subjects;

                console.log($scope.subjects);

 

            })

            .error(function (error) {

                $scope.status = 'Unable to load subject data: ' + error.message;

 

            });

    };

});

 

In this way, we can easily fetch data from the database and bind it to the bootstrap dropdown in an AngularJS application. I hope you found this post useful. Thanks for reading!


Comments  (2 )

Saad Benbouziud
on Thu, Oct 29 2015 5:43 AM

dafuq went wrong with the indentation ? :o

Gopinath Ashokan
on Tue, Nov 22 2016 11:18 AM

Hi.. I tried your post. It is great.

In my case, I want to render the dropdown menu inside an ng-repeat and also it has to bind to data from API.

My code is,

<ul class="nav nav-tabs list clearfix" id="myTab">

                   <li class="item"><a href="#">Home & Garden </a></li>

                   <li ng-repeat="category in categories" class="item dropdown">

                       <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="dropdownMenu{{$index}}" aria-haspopup="true" aria-expanded="true">{{$index}}   <span class="caret"></span></a>

                       <ul class="dropdown-menu" aria-labelledby="dropdownMenu{{$index}}">

                           <li ng-repeat="a in category.subcategories"><a href="#">{{subcategory.name}}</a></li>

                       </ul>

                   </li>

               </ul>

In this when the parent array "$scope.categories" is static, the dropdown toggle is working. But its value is from API $http call, the dropdown toggle is not working. Can you please help me to resolve this?

Thanks