问题描述
我想这
$scope.name = 'Angular';
$scope.list = ['foo: {{name}}', 'bar: {{name}}'];
<div ng-repeat="template in list" compile="template"></div>
是
<div real="foo: Angular"></div>
<div real="bar: Angular"></div>
所以我用$编译:
So i use $compile:
$compileProvider.directive('compile', function ($compile) {
return function (scope, element, attrs) {
scope.$watch(
function (scope) {
return scope.$eval(attrs.compile);
},
function (value) {
//element.html(value);
//$compile(element.contents())(scope);
element.attr("real", value);
element.removeAttr("compile");
$compile(element)(scope);
}
);
};
})
但是,它的输出:
but, it output:
<div real="foo: Angular"></div>
<div real="foo: Angular"></div>
<div real="bar: Angular"></div>
<div real="bar: Angular"></div>
有啥问题?
演示:
推荐答案
试试这个:
<div ng-repeat="template in list">
<div compile="template"></div>
</div>
说明
当你把你的指令,在相同的元素与 NG-重复
并调用 $编译(元)(范围);
,你的元素编译 包括NG-重复的,引起了 NG-重复
来运行一个多时间。当我还删除该指令NG重复,它的工作原理:
When you put your directive on the same element with ng-repeat
and call $compile(element)(scope);
, your element is recompiled including the ng-repeat, causing the ng-repeat
to run one more time. When I also remove the ng-repeat in the directive, it works:
element.attr("real", value);
element.removeAttr("compile");
element.removeAttr("ng-repeat");
$compile(element)(scope);
不建议使用此解决方案,因为我们硬code中的 element.removeAttr(NG重复);
This solution is not recommended because we hard-code the element.removeAttr("ng-repeat");
请记住,也适用优先级:1500
和端子:真正的
的指令,以避免再次编译角有后编译元素:
Remember to also apply priority:1500
and terminal:true
to the directive to avoid compiling again after angular has compiled the element:
$compileProvider.directive('compile', function($compile) {
return {
priority:1500,
terminal:true,
link: function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
//element.html(value);
//$compile(element.contents())(scope);
element.attr("real", value);
element.removeAttr("compile");
$compile(element)(scope);
}
);
}
};
});
有关这两个设置的更多信息。查看Add在AngularJS
For more information about these 2 settings. Check out Add directives from directive in AngularJS
这篇关于AngularJS - ngRepeat应用双重时候$编译元素的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!