Book Image

AngularJS Directives Cookbook

By : Monteiro
Book Image

AngularJS Directives Cookbook

By: Monteiro

Overview of this book

AngularJS directives are at the center of what makes it such an exciting – and important - web development framework. With directives, you can take greater control over HTML elements on your web pages – they ‘direct’ Angular’s HTML compiler to behave in the way you want it to. It makes building modern web applications a much more expressive experience, and allows you to focus more closely on improving the way that user interaction impacts the DOM and the way your app manages data. If you’re already using Angular, you probably recognize the power of directives to transform the way you understand and build your projects – but customizing and creating your own directives to harness AngularJS to its full potential can be more challenging. This cookbook shows you how to do just that – it’s a valuable resource that demonstrates how to use directives at every stage in the workflow. Packed with an extensive range of solutions and tips that AngularJS developers shouldn’t do without, you’ll find out how to make the most of directives. You’ll find recipes demonstrating how to build a number of different user interface components with directives, so you can take complete control over how users interact with your application. You’ll also learn how directives can simplify the way you work by creating reusable directives – by customizing them with Yeoman you can be confident that you’re application has the robust architecture that forms the bedrock of the best user experiences. You’ll also find recipes that will help you learn how to unit test directives, so you can be confident in the reliability and performance of your application. Whether you’re looking for guidance to dive deeper into AngularJS directives, or you want a reliable resource, relevant to today’s web development challenges, AngularJS Directives Cookbook delivers everything you need in an easily accessible way.
Table of Contents (11 chapters)
10
Index

Creating a simple modal directive

Modal windows are interface components often used in web applications. Building them is very simple and is done using libraries such as Dojo or jQuery, but implementing them in AngularJS applications is not as simple, since the DOM manipulation is restricted to directives.

Next, we will see how to use this component in a very simple way.

Getting ready

Let's start placing the following HTML code in a new blank page. The following code has all the basic requisites to illustrate the example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.x/angular.js"></script>
<title>Modal Window Directive</title>
<style>
  .modal-overlay {
  position:absolute;
  z-index:9999;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color:#000;
  opacity: 0.8;
}
.modal-background {
  z-index:10000;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;

}
.modal-content {
  padding:10px;
  text-align: center;
}
.modal-close {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 5px;
  cursor: pointer;
  display: inline-block;
}
</style>
</head>
<body ng-app='SimpleModal'>
</body>
</html>

For this simple example, we placed the CSS code inside the style tag on the same HTML file; don't do that in production.

How to do it…

  1. Now we can create our modal directive with the following code:
    // Creating a simple Modal Directive
    app = angular.module('SimpleModal', []);
    
    app.directive('modalWindow', function() {
      return {
        restrict: 'E',
        scope: {
          show: '='
        },
        replace: true, // Replace with template
        transclude: true, // To use custom content
        link: function(scope, element, attrs) {
    
          scope.windowStyle = {};
    
          if (attrs.width) {
            scope.windowStyle.width = attrs.width;
          }
          if (attrs.height) {
            scope.windowStyle.height = attrs.height;
          }
    
          scope.hideModal = function() {
            scope.show = false;
          };
        },
        template: "<div ng-show='show'><div class='modal-overlay' ng-click='hideModal()'></div><div class='modal-background' ng-style='windowStyle'><div class='modal-close' ng-click='hideModal()'>X</div><div class='modal-content' ng-transclude></div></div></div>"
      };
    });
  2. Add the controller's code:
    app.controller('ModalCtrl', ['$scope',
      function($scope) {
        $scope.modalShown = false;
        $scope.toggleModal = function() {
          $scope.modalShown = !$scope.modalShown;
        };
      }
    ]);
  3. Finally, include the directives tags into the body tag of our HTML file:
    <div ng-controller='ModalCtrl'>
      <button ng-click='toggleModal()'>Open Modal</button>
      <modal-window show='modalShown' width='400px' height='60%'>
      <p>Hello Simple Modal Window<p>
      </modal-window>
    </div>

How it works…

The work here is very simple; we just placed an HTML template using the inline template, as we did in the previous example:

template: "<div ng-show='show'><div class='modal-overlay' ng-click='hideModal()'></div><div class='modal-background' ng-style='windowStyle'><div class='modal-close' ng-click='hideModal()'>X</div><div class='modal-content' ng-transclude></div></div></div>"

As we build everything from scratch, we need to style the HTML tags with CSS classes for a better look using the style tag inside the head element. In production applications, you must have a separated file for CSS styles.

The inline template contains the built-in directives ng-show() and ng-style(), along with a ng-click() function to hide the modal.

The ng-style() directive is not used often, but we include it in this example just to illustrate how we can place inline styles inside a directive.

Inline templates are very useful, but not too flexible. On large application managers, different inline templates can be very painful to use and take a lot of time. Use them with small templates. In the next recipe, we will see how to use external templates on custom directives.

There's more…

We can also use the ng-transclude in-built directive to remove any content from the DOM before the modal content inserted.

See also