in this example
myApp.directive("customHeading",function(){
var index = 1;
return{
restrict : "E", // restrict element
templateUrl : "./views/custom-card.html",
//scope : {},
controller : function($scope){
console.log(`In controller ${index}`);
$scope.cardNumber = 'This is card '+index++;
//index++;
}// end controller
};
html =>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
My doubt is why only return object is manipulated every time we use custom-heading directive? Usually index should be assigned to 1 each time we use customHeading directive but that's not the case. I tried and found that only functions inside return are executed every time the directive is used. Is it something related to directive's instance which is created only once. Could someone explain what's happening at the background?
If we use same controller twice, whether in diff views or in same page or nest them , and assign index as 1 and then increment and log its value we see that index value will be reassigned each time we use that controller and that's because controller function is executed each time.
In case of directives only the functions (controller , link etc.) inside return object are executed again and again no matter how many times we use that directive. and not what is written before that return and that is what I want to know. Why only functions inside return are executed. My doubt is not regarding scope at all. Ideally whole callback function of directive should be executed whenever we use . But only return part is executed.
myApp.directive("customHeading",function(){
var index = 1;
console.log(" In directive"); // It's logged only once
return{
restrict : "E", // restrict element
templateUrl : "./views/custom-card.html",
//scope : {},
controller : function($scope){
console.log(`In controller`); // Logged 3 times
$scope.cardNumber = 'This is card '+index++;
//index++;
}// end controller
};
HTML =>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
<custom-heading></custom-heading>
In console we get this as o/p =>
In directive
In controller
In controller
In controller
Now, if anyone could explain why "In directive " is logged only once. Controller is behaving as expected.
Aucun commentaire:
Enregistrer un commentaire