AngularJS Tutorial - Directives








AngularJS directives allows us to create new HTML elements.

A built-in directive is one that ships out of the box with Angular.

All built-in directives are prefixed with the ng namespace.

The following code uses ng-app built-in directives.

<html ng-app="myApp">
    ...
</html>

Inside of our <html> element, we can use any of the built-in or custom directives.

All of the directives we use within the root element will have access to $rootScope

Custom Directives

Let's create a custom html tag:

<my-directive></my-directive>

Invoking a directive means to run the associated JavaScript that sits behind the directive.

Declaring a directive is like putting a function within our HTML as an element, attribute, class, or comment.

The myDirective directive definition looks like:

angular.module('myApp',  [])
  .directive('myDirective',  function()  {
     return  {
       restrict: 'E',
       template:  '<a href="http://java2s.com"> Click me</a>'
     }
});

The above JavaScript is called a directive definition.

We register new directives by providing a name as a string and function.

The name of the directive should always be pascalCased, and the function should return an object.

The tag name of directive is my-directive, and the directive definition would be myDirective.

The object returned from the .directive() method comprises methods and properties that configure our directive.

By default, Angular nests the HTML template string inside of our custom HTML tag, <my-directive>, in the generated source code.

To remove custom element (<my-directive>) and output only the template string, set the replace option to true:

angular.module('myApp',  [])
  .directive('myDirective',  function()  {
    return  {
      restrict: 'E',
      replace:  true,
      template:  '<a href="http://java2s.com"> Click me</a>'
    }
});





Directives restrict

We can create directives and place them in several spots.

  • <my-directive></my-directive> uses directives in element tag
  • <div my-directive></div> uses directives as attribute
  • <div class="my-directive"> uses directives as attribute value
  • <!-- directive: my-directive --> uses directives in comments

To allow Angular to invoke our directive, we need to change the restrict option.

This restrict option tells AngularJS which formats to look for when compiling the HTML.

We can specify one or many formats.

The following definition tells AngularJS that my-directive can be invoked as an element (E), an attribute (A), a class (C), or a comment (M):

angular.module('myApp',  [])
.directive('myDirective',  function()  {
     return  {
          restrict: 'EACM',
          replace:  true,
          template:  '<a href="http://java2s.com">Click me</a>'
     };
});