Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS how to create a reusable template for Bootstrap modal

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;
    }
  }
});
like image 557
Dragonfly Avatar asked Sep 05 '14 14:09

Dragonfly


2 Answers

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';
};
like image 133
Dragonfly Avatar answered Nov 16 '22 04:11

Dragonfly


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

like image 28
alpinescrambler Avatar answered Nov 16 '22 02:11

alpinescrambler