Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Introduction to the directives in AngularJS

1. Introduction

Following the AngularJS documentation itself ,
the directives are marks in the elements of the DOM tree, in the nodes of the HTML, which indicate to the Angular compiler that it
must assign certain behavior to said elements or transform them accordingly.

We could say that the directives allow us to add dynamic behavior to the DOM tree making use of the
native ones of the AngularJS itself or extend the functionality to where we need creating our own.
In fact, the recommendation is that it is in the directives in the only place where we manipulate the DOM tree, so that it falls
within the life cycle of compiling, binding and rendering the HTML.

The directives are the technique that will allow us to create our own visual components
encapsulating the possible complexities in the implementation, normalizing and parametrizing them according to our needs.

In this tutorial we will see what types of policies exist and basic examples of both native and native directives as an introduction
so that we can get an idea of ​​what they are for and how far we can go with them.

2. Environment

The tutorial is written using the following environment:

  • Hardware: MacBook Pro 15 ‘laptop (2.3 GHz Intel Core i7, 16GB DDR3).
  • Operating System: Mac OS Mavericks 10.9.4
  • AngularJS 1.4.0.
  • Plunker

3. Types.

The first type of directives we have already commented: there are native directives from Angular and anyone
can create their own directives or make use of third-party directives.

In the following code we can find the following directives:

  • ng-app (ngApp): is the native Angular directive that starts our application by establishing the root element of it.
  • ng-controller (ngController): is the native directive that associates a view with the controller that maintains the linkage of the model and manages the control events of it.
  • ng-model (ngModel): is the native directive that links a particular property of the model declared in the controller to a component of the view; normally to a form component to obtain information.
  • btn-radio (btnRadio): is an angular-bootstrap directive that transforms a tag into a radio button component of bootstrap

Normally, directives starting with ng * are Angular and each module has its own prefix, but it does not have that, in fact bootstrap directives do not.

The second typology that we can find in the directives is its Scope of application to the nodes of the DOM tree, in such a way that they can be associated:

  • by declaring an ‘A’ attribute in any element of the DOM
  • by declaring a css class ‘C’ in any class attribute of a DOM element
  • by assigning an ‘M’ comment in any commented code block
  • by declaring an ‘E’ element of the DOM tree itself
  • you can also combine the declaration of an element with the assignment of an attribute ‘EA’ or also add the declaration in a comment ‘EAC’

The normal thing is to arrange and declare directives at the element and attribute level.

4. Native directives.

As we saw in the first steps with AngularSJS
we have a series of native directives that allow us to link the AngularJS model to the view, exposing it through a controller.

You can access the documentation of the Angular directives to verify that there are enough directives
to more than support the needs of any SPA application and it is striking that even the standard HTML5 form components are coated with a directive, which
basically allows associate a property of the model to the form component.

I refer at this point to the documentation and the example proposed in the previous point, to focus on the following.

5. Own directives.

When creating directives, the recommendation is that they be named with camelCase and to refer to them they are separated with hyphens;
although other techniques could be used when using scripts we avoid errors if we use tools that validate our HTML.

The following code we can see how to declare a directive in an existing module:

(function() {
  angular.module(‘tnt.ui.components’)
  .directive(‘userInfo’, [function() {
    return {
      restrict: ‘E’,
      template:‘Frist name: {{user.name}}, email: {{user.email}}’
    };
  }]);
}());

To make use of it, the following code would suffice:

The directive assumes that the scope of the controller has a “user” property with the information to be rendered by the user:

Next we will see all the available parameters for the declaration of a directive and we will verify that
the seen thing is not the most advisable way if we want that our directive is really reusable.

Here you have a plunker with the code of this first directive:

4.1 API.

When declaring a directive we can assign the following properties:

  • restrict : to delimit the declaration scope of the directive to an attribute, element, style or comment. It is the type of directives that we saw previously and is specified with a literal ‘A’, ‘E’, M, ‘C’ or ‘EA’.
  • template : specifies the HTML code that will be compiled in the scope of the directive by applying the properties defined also in the scope of the same
  • templateUrl : the recommendation is that when the template code becomes too large it is externalized in a separate html file to which the templateUrl property that is like a ngInclude could point,
  • scope : all the directives have an associated field that by default is that of their father, it is normal to be a controller.
    Through this attribute, which can adopt the following values, it can be modified:
    • false : it is the default behavior, it inherits the scope and any modification both inside
      and outside the directive of a property of the model will be reflected in both directions,
    • true : a new scope is created by making a copy of the parent’s scope in such a way that,
      as a new scope, the changes in the model that are made within the directive will not be
      reflected to the outside, but the modifications in the model of the scope of the father if they will have
      reflection in the scope of the directive,
    • {} : a new scope independent of the parent will be created; is the recommended field so that
      a directive can really be reused and does not depend on or inherit all the scope of his father. Although,
      within the scope declaration values ​​can be passed by specifying a series of prefixes that will
      allow not only to pass properties of the model of the scope of the father but to link them in one or both directions.
      These properties are declared as attributes of the HTML element of the policy. A) Yes:
      • @ : linking in one direction, when the scope of the directive is created, the value of
        this property is assigned to the new scope in such a way that the modifications within the directive
        do not affect the scope of the parent but the contras. The value of the property must be evaluated {{}}
        in the declaration of the attribute.
      • = : linkage in both directions, expects the value of the property to be a
        reference to the model, not an evaluable expression as in the previous case. The link is made in
        both directions in such a way that modifications both outside and within the directive of the model
        affect both.
      • & : linking of methods that allows to invoke methods
        declared in the father’s domain from the directive

      Finally, all these prefixes can be accompanied by a redefinition of the name of the property in the
      field.

      On the initial example we will make the following modifications in the directive statement:

(function() {
  angular.module(‘tnt.ui.components’)
  .directive(‘userInfo’, [function() {
    return {
      restrict: ‘E’,
      scope:{
        name: ‘@’,
        email: ‘@’,
        rate: ‘=’,
        click: ‘&’
      },
      template:
    };
  }]);
  
  angular.module(‘tnt.ui.components’).controller(‘DemoDirectivesCtrl’, function($scope){
  $scope.users = [{
    name: ‘Jose’,
    email: [email protected],
    rate: ‘1’
  },
  {
    name: ‘Gustavo’,
    email: [email protected],
    rate: ‘2’
  }
  ];
  
  $scope.vote = function(user){
    console.log(user);
  };
});
}());

We adapt the HTML code to the parameters that the directive now receives and we verify that now,
the directive is totally reusable:

  • link : define a function with the following contract function link (scope, element, attrs) {…} receiving the scope of the directive, the element of the DOM tree to which the directive is linked, wrapped by an object of the jQuery implementation of Angular ‘jqLite’ and an object with the name and value pairs of the policy attributes declared in the HTML element.
    Through the element parameter and being able to access both the scope and, as a consequence, the value of the properties as well as the attributes it receives, whether or not they are declared in the scope, the HTML node and all its children can be manipulated before rendering.
  • transclude : adopting the value to true allows you to create directives that encapsulate other directives or wrap portions of code with a wrapper allowing you to insert the code wrapped in the template with the directive
  • require : allows you to declare parameters in the directive that refer to other directives as abligatory.
  • controller : allows declaring a controller at the policy level. The difference between the link function is that the controller code is executed before
    the compilation and that of the link afterwards. DOM tree manipulation should not be included in a controller that should be
    reserved for initialization or manipulation of policy scope properties.

The post Introduction to the directives in AngularJS appeared first on Target Veb.



This post first appeared on Targetveb, please read the originial post: here

Share the post

Introduction to the directives in AngularJS

×

Subscribe to Targetveb

Get updates delivered right to your inbox!

Thank you for your subscription

×