I've been playing with angular directive recently and I have couple of question with regards to the link and compile functions.
I have the following two directives, which have the same funcitonality:
App.directive('repeatX', function(){
return {
transclude: 'element',
compile: function(element, attr, linker){
console.log('Compile repeatX');
return function(scope, $element, attrs, ctrl){
console.log('Link repeatX');
var parent = $element.parent();
for(var i = 0; i < Number(attrs.repeatX) - 1;i++){
var childScope = scope.$new();
linker(childScope, function(clone){
$element.after(clone.attr('repeat-x', 0));
});
}
}
}
}
});
App.directive('repeatX2', function(){
return {
compile: function(element, attrs){
console.log('Compile repeatX2');
for(var i = 0; i < Number(attrs.repeatX2) - 1;i++){
element.after(element.clone().attr('repeat-X2', 0));
}
return function(){
console.log('Link repeatX2');
}
}
};
});
It seems that the two directive are pretty much doing the same thing, but I quite don't understand why Compile repeatX2
is displayed n
times whereas the Compile repeatX
only once.
The second question is, what is the exact job of the linker
function?
I have a working example here: http://jsbin.com/rugohido/10/edit