如何写一个“双”和“ntimes'指令为angularjs? [英] how to write a 'double' and a 'ntimes' directive for angularjs?
问题描述
我无法理解ngRepeat'指令,所以我希望学习如何写一个'双'指令,然后用一个ntimes'指令扩展angularjs作品:
所以
双师型
<双>
< H1>的Hello World< / H1>
< /双>
将导致生产
< H1>的Hello World< / H1>
< H1>的Hello World< / H1>
'ntimes'
< ntimes重复= 10 -10
< H1>的Hello World< / H1>
< / ntimes>
将导致生产
< H1>的Hello World< / H1>
.... 8次以上....
< H1>的Hello World< / H1>
<双>
< H1>的Hello World - 2'; / H1>
< /双>&所述; ntimes重复= 10 -10
< H1>的Hello World - 10 LT; / H1>
< H4>更多文字< / H4>
< / ntimes>
该指令下面将删除<双&GT中,< /双&GT中,< ntimes ...>
和< / ntimes>
标签:
VAR应用= angular.module('应用',[]);
app.directive('双',函数(){
返回{
限制:'E',
编译:功能(tElement,ATTRS){
VAR内容= tElement.children();
tElement.append(content.clone());
tElement.replaceWith(tElement.children());
}
}
});
app.directive('ntimes',函数(){
返回{
限制:'E',
编译:功能(tElement,ATTRS){
VAR内容= tElement.children();
对于(VAR I = 0; I< attrs.repeat - 1;我++){
tElement.append(content.clone());
}
tElement.replaceWith(tElement.children());
}
}
});
我用一个编译函数,而不是一个链接功能,因为它似乎只要求模板DOM操作。
更新:我喜欢这个实施ntimes的编译功能更完善:
编译:功能(tElement,ATTRS){
VAR内容= tElement.children();
变种repeatedContent = content.clone();
对于(VAR I = 2; I< = attrs.repeat;我++){
repeatedContent.append(content.clone());
}
tElement.replaceWith(repeatedContent);
}
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'
<double>
<h1>Hello World</h1>
</double>
would result in producing:
<h1>Hello World</h1>
<h1>Hello World</h1>
'ntimes'
<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());
}
}
});
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);
}
这篇关于如何写一个“双”和“ntimes'指令为angularjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!