• Note that we have added a custom template to display the modal called myModalContent.html. Open your Terminal window inside the application folder and type:
    grunt dev

    The result expected when the modal button is clicked is what we have in the following screenshot:

    How to do it…
  • We can easily extend this functionality by creating a custom directive and an external template, as already mentioned earlier. To do this, perform the following steps and add the following code to your application:
    .controller('ModalCustomCtrl', function ($scope) {
      // Set show modal to false/ hide from HTML
      $scope.showModal = false;
    
      // Toggle function to show and hide modal from HTML
      $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
      };
    })
    // Modal Directive
    .directive('modal', function () {
      return {
        // Add a custom template for modal
        templateUrl: 'app/home/modal-tpl.html',
        restrict: 'E',
        transclude: true,
        replace:true,
        scope:true,
        link: function postLink(scope, element, attrs) {
          scope.title = attrs.title;
    
          scope.$watch(attrs.visible, function(value){
            if(value == true)
              $(element).modal('show');
            else
              $(element).modal('hide');
          });
    
          $(element).on('shown.bs.modal', function(){
            scope.$apply(function(){
              scope.$parent[attrs.visible] = true;
            });
          });
    
          $(element).on('hidden.bs.modal', function(){
            scope.$apply(function(){
              scope.$parent[attrs.visible] = false;
            });
          });
        }
      };
    })

 

As we are extending a directive, we will use an external template called modal-tpl.html to demonstrate the flexibility of this directive. Let’s add the following HTML code:

<div class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">{{ title }}</h4>
      </div>
      <div class="modal-body" ng-transclude></div>
      <div class="modal-footer">
        <button class="btn btn-danger" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>