How it works…

It is very simple to use the Angular UI Bootstrap components on Angular applications. Note that the generator we use already has Bootstrap installed and configured, though it is very simple to do this.

Tip

You can find more about the Angular Bootstrap UI on the official website at http://angular-ui.github.io/bootstrap/.

In this example, we only use the Bootstrap built-in directive to enable a modal component. However, we don’t have direct contact with the directive’s code.

In the second example, we extended this control and created our own directive called modal using a custom template:

// 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;
        });
      });
    }
  };
})

To use it, we only need to declare it in our markup, within the given controller, as shown in the following example:

<!-- Custom Modal -->
<div ng-controller="ModalCustomCtrl">
  <div style="width:600px; margin:0 auto; text-align:center">
  <button ng-click="toggleModal()" class="btn btn-default">Open modal custom Directive</button>
  </div>
  <!-- Modal from Custom Directive-->
  <modal title="Modal Custom Directive" visible="showModal">
    Content Modal from: <b>Custom Directive</b>
  </modal>
</div>

With just a few lines of code, we have a very flexible custom modal directive.

There’s more…

The ui-bootstrap-tpls.js file has all the Bootstrap templates inline on the JavaScript file using the $templateCache function:

angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/modal/window.html", "<div tabindex=\"-1\" role=\"dialog\" class=\"modal fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" + " <div class=\"modal-dialog\" ng-class=\"{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}\"><div class=\"modal-content\" modal-transclude></div></div>\n" + "</div>");
}]);

Tip

It is also possible to use dynamic content to fill the modal’s body content; we will see an example of this in the next topic.