Angular - Directives

Directives

Compile Function

Only to be used to modify the template. It has 1-1 relation to the directive which means it will be applied only once to the directive

Link Function

Has access to scope which the compile function doesn't have. This is because the scope for the directive is created after calling the compile function.  This is used for binding the values between the scope and its template. It has N-1 relation with the directive and 1-1 with each directive instance. 

  • Reading Values - To read values from DOM inside the link function the best option is to use $watch
function linkFunction ( scope, .. ){
    scope.$watch( attrs.demoGreet, function(){
        lElement.text( "Hello  , "+ name );
    }
}

  • Writing Values - To write values to the DOM from the link function the best option is $apply. If the element is coming from jQuery or DO we need to call apply as these are outside the angular domain.

lElement.bind( 'click' , function (){
    console.log('click');
    scope.$apply( function(){
        parse( attrs.demoGreet ).assign( scope, abc);
    }
}

restrict :

A - Attribute
C - Class
E - Element
M - Comments

scope :

true - Creates a new scope which prototypically inherits from the parent scope
{} - Isolated scope with in inheritance


transclusion :

true 
  • Keeps the content (innerHTML) within the new directive.
  • It creates the scope of the directive as sibling of the transcluded contents' scope. This way the transcluded content has correct prototypical access  to its parent scope and is not clobbered by the scope of the new directive.

No comments:

Post a Comment