简体   繁体   中英

Where to listen for events and manipulate DOM(compile, link) in AngularJS?

app.directive('appView', ['appService',function($scope) {   

return {
    restrict    : '',
    template    : '',
    templateUrl : 'app/app.html',   
    controller  : function($scope,docsService){         

                  },
    compile : function(tElement, tAttrs, transclude){
                tElement.bind('click', function() {
                console.log("In compile");
               //Update DOM element
              });

    },
    //or
    /*
    link : function(scope, element, attrs) {
             element.bind('click', function() {
             console.log("In link");
             //Update DOM element.   
        });
    },*/


};  

}]);    

I am exploring AngularJS and came across the fact that, compile and link won't work together,
Now, To manipulate DOM and to listen for the events, what is the best practice here, to use link or compile? and why choose one over the other? link has a scope attribute and can be more flexible I guess.

From Angular docs on $compile :

The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often. Examples that require compile functions are directives that transform template DOM, such as ngRepeat, or load the contents asynchronously, such as ngView.

And:

The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

So in most cases the link function is sufficient. You can add listeners and manipulate the DOM, if necessary. The compile function is necessary for more "extreme" cases, like ng-repeat . (Statistically from my experience of ~14 months with Angular, I have only once used compile .)

By the way (again from docs):

A compile function can have a return value which can be either a function or an object.

  • returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.

  • returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM