简体   繁体   中英

Why compile running multiple times - Angular Directive

In the following snippet, I want to ask that if compile phase runs only once for all the instances of a directive, then why am I seeing console.log("compile") run 5 times? It should have run only once? Isn't it?

 //module declaration var app = angular.module('myApp',[]); //controller declaration app.controller('myCtrl',function($scope){ $scope.name = "Joseph"; }); //app declaration app.directive('myStudent',function(){ return{ template: "Hi! Dear!! {{name}}<br/>", compile: function(elem, attr){ console.log("compile"); } } }); 
 <body ng-app="myApp" ng-controller="myCtrl"> <my-student></my-student> <my-student></my-student> <my-student></my-student> <my-student></my-student> <my-student></my-student> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> </body> 

HTML compilation happens in three phases:

  1. $compile traverses the DOM and matches directives.

    If the compiler finds that an element matches a directive, then the directive is added to the list of directives that match the DOM element. A single element may match multiple directives.

  2. Once all directives matching a DOM element have been identified, the compiler sorts the directives by their priority.

    Each directive's compile functions are executed. Each compile function has a chance to modify the DOM. Each compile function returns a link function. These functions are composed into a "combined" link function, which invokes each directive's returned link function.

  3. $compile links the template with the scope by calling the combined linking function from the previous step. This in turn will call the linking function of the individual directives, registering listeners on the elements and setting up $watchs with the scope as each directive is configured to do.

From Angular documentation "What are Directives? At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (eg via event listeners), or even to transform the DOM element and its children."

So when angular compiles the html, it traverse through the mark up and whenever it finds <my-student></my-student> mark up it will try attaching "the specific behaviour". To get the specific behavior it need to compile the directive each time since each instance of directives might have different attributes or parameters.

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