Custom Directives

Description

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.

Example

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





















Home »
  AngularJS »
    AngularJS Tutorial »




Introduction
Buildin Filters
Buildin Directives