I am having trouble understand the 'ngRepeat' directive so I wish to learn how angularjs works by writing a 'double' directive and then extending with an 'ntimes' directive: so
<double>
<h1>Hello World</h1>
</double>
would result in producing:
<h1>Hello World</h1>
<h1>Hello World</h1>
<ntimes repeat=10>
<h1>Hello World</h1>
</ntimes>
would result in producing:
<h1>Hello World</h1>
.... 8 more times....
<h1>Hello World</h1>
<double>
<h1>Hello World - 2</h1>
</double>
<ntimes repeat=10>
<h1>Hello World - 10</h1>
<h4>More text</h4>
</ntimes>
The directives below will remove the <double>, </double>, <ntimes ...>
and </ntimes>
tags:
var app = angular.module('app', []);
app.directive('double', function() {
return {
restrict: 'E',
compile: function(tElement, attrs) {
var content = tElement.children();
tElement.append(content.clone());
tElement.replaceWith(tElement.children());
}
}
});
app.directive('ntimes', function() {
return {
restrict: 'E',
compile: function(tElement, attrs) {
var content = tElement.children();
for (var i = 0; i < attrs.repeat - 1; i++) {
tElement.append(content.clone());
}
tElement.replaceWith(tElement.children());
}
}
});
Fiddle
I used a compile function rather than a linking function because it seemed like only template DOM manipulation was required.
Update: I like this implementation of the ntimes compile function better:
compile: function(tElement, attrs) {
var content = tElement.children();
var repeatedContent = content.clone();
for (var i = 2; i <= attrs.repeat; i++) {
repeatedContent.append(content.clone());
}
tElement.replaceWith(repeatedContent);
}
The ng-repeat
directive is mainly used to iterate over items on lists/arrays/collections (i.e. ng-repeat="item in list"
) and does much more than simply cloning elements. Please take a look at angularjs ng-repeat directive documentation.
If you really just want to clone elements, try something like this: http://jsfiddle.net/hp9d7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With