我无法理解“ngRepeat”指令,因此我希望通过编写“double”指令然后使用“ntimes”指令扩展来了解 angularjs 的工作原理: 所以
'双'
<double>
<h1>Hello World</h1>
</double>
将导致产生:
<h1>Hello World</h1>
<h1>Hello World</h1>
'n次'
<ntimes repeat=10>
<h1>Hello World</h1>
</ntimes>
将导致产生:
<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>
下面的指令将删除 <double>, </double>, <ntimes ...>
和 </ntimes>
标签:
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());
}
}
});
我使用编译函数而不是链接函数,因为它似乎只需要模板 DOM 操作。
更新:我更喜欢这个 ntimes 编译函数的实现:
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);
}
关于javascript - 如何为 angularjs 编写 'double' 和 'ntimes' 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13852248/