Angular.js:动态编译ng-repeat [英] Angularjs: Compile ng-repeat dynamically
问题描述
我发现Angularjs有一些奇怪的行为.我的指令只是将 ng-repeat
添加并编译到我的dom元素中.但是,范围变量 item
无法访问.查看下面的代码以获取解释.
I have found some strange behavior with Angularjs. My directive simply adds and compiles ng-repeat
to my dom element. However the scope variable item
is not accessible. Look at the code below for explanation.
var demo = angular.module('demo', []);
demo.directive('customRepeat', function($compile) {
return {
priority: 2000,
restrict: 'A',
compile: function(element){
element.attr('ng-repeat', 'item in [1,2,3,4,5,6]')
return function(scope, element) {
$compile(element)(scope)
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app='demo'>
<h3>My Items</h3>
<div custom-repeat>
Item: {{item}}
</div>
</div>
谁有一些Angularjs技能来解决这一问题?
Who has some Angularjs skills to figure this one out?
尝试使用较旧版本的Angularjs(例如1.2.x)运行它,您将看到它按预期工作.
N.B. Try and run this with an older version of Angularjs (say 1.2.x) and you will see that it works as intended.
推荐答案
修改原始DOM时编译指令的正确方法是,从像 var compileFn =这样的指令编译函数中创建
,然后在内部链接函数中使用喜欢的 compileFn
.$ compile(element) scope
重新编译元素.这样,您还将在Angular 1.2.X&中看到最大调用堆栈超出错误
.1.6.X版本.通过打开控制台,检查 此导航器 .
The correct way to compile directive when raw DOM is modified is, create compileFn
from directive compile function like var compileFn = $compile(element)
and then inside link function recompile element with liked scope
. That way you will also see Maximum call stack exceed error
in both Angular 1.2.X & 1.6.X version. Check this plunker by opening console.
基本上是怎么回事,您要在指令元素&上添加 ng-repeat
再次重新编译该元素,这将导致再次编译 customDirective
,并且此过程将继续无限进行.因此,在再次编译元素之前,应确保已删除 custom-report
指令属性.这将不允许 custom-report
无限执行.
Basically what happening is, you are adding an ng-repeat
on directive element & recompiling that element once again which will lead to compilation of customDirective
once again, and this process will keep on happening infinitely. So before compiling element once again, you should make sure that you had removed custom-report
directive attribute. That will not allowed to custom-report
infinite execution.
var demo = angular.module('demo', []);
demo.directive('customRepeat', function($compile) {
return {
priority: 2000,
restrict: 'A',
compile: function(element){
element.attr('ng-repeat', 'item in [1,2,3,4,5,6]')
element.removeAttr('custom-repeat');
//this line is need for compilation of element
var compile = $compile(element);
return function(scope, element) {
compile(scope); //linking scope
}
}
}
});
这篇关于Angular.js:动态编译ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!