Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Understanding Custom Directives in AngularJS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.07k
    Comment on it

    AngularJs Directives are used on a DOM element like any attribute, name of the element, some css class or any comment. It tells AngularJS’s html compiler to attach any directive to DOM element. all data bind attributes with ng- are in-built directives like ng-app, ng-controller in angularjs.

    Custom directives are those directives which have their own functions and run when DOM is compiled. If you want to reuse the lines of code in your application for different pages without repeating the lines of code in every place, in this case you can create a directive with that code in separate file and call that directive where that code is needed. This is the better way to understand code. These are the types of custom directives:

    * Element directives
    * Attribute directives
    * CSS class directives
    * Comment directives

    Element directives:
    To use directive as an element you have to write element tag. If you want to use some code, then you just need to use that tag.

    html:
     

    <user-reviews>.</user-reviews>

    JS:
     

    myapp.directive(userReviews', function() {
      return {
        restrict    : 'E',  // used E because of element
        templateUrl : 'custom-directives/reviews.html'
      };
    });

    In the above example we have created a directive defined by myapp.directive. It is named as userReviews that is the element tag name used in html. user-reviews is different from userReviews because hyped in user-reviews is converted into camel case written as userReviews in javascript file. then it has a function which returns restrict: ‘E’ that means custom element directive and templateUrl that has the path of the code file inside element tag.

    Attribute directives:

    It works same as element directive, the only difference is that it returns attribute tag.

    HTML:
     

    <div user-reviews> ... </div>

    JS:
     

    app.directive(userReviews', function() {
      return {
        restrict    : 'A', // used A because of attribute
        templateUrl : 'custom-directives/reviews.html'
      };
    });

     

    CSS Directive − It is used when a matching css style is encountered.
    Comment Directive− It is used when a matching comment is encountered.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: