How to create a Modal in AngularJS

Posted By : Mayank Jain | 31-Oct-2018

$uibModal creates modal windows. It is easy and straightforward - we have to create a template and controller and reference them when using $uibModal.

To use $uibModal directive we first need UI Bootstrap which can be downloaded from here. As soon as we've got all the files downloaded and included in our page we just need to declare a dependency on the ui.bootstrap module - 

var app = angular.module('mySampleModule',['ui.bootstrap',...]);

Now, we can include our modal directive. Also, we have to include $uibmodal in the controller to use (ui.bootstrap) modal directive.

In Controller

app.controller('mySampleController', ['$uibModal', function ($uibModal) {}]);

Now, we can use $uibModal in our controller. The $uibModal service has only one method - open(options). We can call this service using a function like this - 

$scope.openSampleModal = function () {
    var modalInstance = $uibModal.open({
      animation: true,
      size: 'lg',
      templateUrl: 'views/modal-template/sampleModal.html',
      controller: 'sampleModalController',
      resolve: {
      }
    });
    modalInstance.result.then(function () {
      
    }, function () {
     
    });
  };

 

HTML-  (sampleModal.html)  


 

 Controller - (sampleModalController)

$uibModal controller for the modal instance, It is either a controller name as a string or an inline controller function, optionally wrapped in array notation for dependency injection. It allows the controller-as syntax. It has a special $uibModalInstance injectable to access the modal instance.

app.controller('sampleModalController', ['$scope','$uibModalInstance', function ($scope,$uibModalInstance){
$scope.close = function () {
      $uibModalInstance.dismiss('cancel');
};
}]);

$close(result) (Type: function) - This method can be used to close a modal, passing a result.

$dismiss(reason) (Type: function) - This method can be used to dismiss a modal, passing a reason.

These methods make it very easy to close and dismiss a modal without a need to create a dedicated controller.

About Author

Author Image
Mayank Jain

Mayank is responsible for implementing visual elements that users see and interact with in a web application.His skillset includes JavaScript, HTML, CSS, AngularJS and Bootstrap.

Request for Proposal

Name is required

Comment is required

Sending message..