AngularJS how to create a reusable template for Bootstrap modal

All we need is an easy explanation of the problem, so here it is.

So I am using the AngularJS Bootstrap modal (http://angular-ui.github.io/bootstrap/). Which is working fine but I was wondering if I could create a basic template that can take in a title and the content.

Then it would populate my template with these info. The template would have a close button, cancel button, overlay, etc. Is there an easy way to do this AngularJS?

This is taken from the example and it’s about what I have. My content is in the templateUrl. It would be nice to pass in the modal template so I don’t have to keep recreating the title and close buttons for every modal I create.

var modalInstance = $modal.open({
  templateUrl: 'myModalContent.html',
  controller: ModalInstanceCtrl,
  size: size,
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Found a way to do it with directives. It opens up a modal with a custom directive that has a template. Then whatever you have in your modal will be inserted into your custom template. This is nice because it holds more than just a message. It can be filled with forms, alert, or anything you want.

This was my directive:

  app.directive('modalDialog', function() {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      link: function(scope) {
        scope.cancel = function() {
          scope.$dismiss('cancel');
        };
      },
      template:
        "<div>" +
          "<div class='modal-header'>" +
            "<h3 ng-bind='dialogTitle'></h3>" +
            "<div ng-click='cancel()'>X</div>" +
          "</div>" +
          "<div class='modal-body' ng-transclude></div>" +
        "</div>"
    };
  });

Modal (‘yourTemplate.html’):

<modal-dialog>
  <div> Your body/message </div>
</modal-dialog>

Javascript:

app.controller('YourController', ['$scope', '$modal', function($scope, $modal) {
  $scope.openModal = function () {
    $modal.open({
      templateUrl: 'yourTemplate.html',
      controller: ModalController
    });
  };
}]);

var ModalController = function ($scope, $modalInstance) {
  $scope.dialogTitle = 'Your title';
};

Method 2

Checkout John Papa’s Hot Towel Angular BootStrap “template”. You can pick it up from there:

https://github.com/johnpapa/HotTowel-Angular/blob/master/NuGet/HotTowel-NG/app/common/bootstrap/bootstrap.dialog.js

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply