ngRepeat由$编译编译不起作用 [英] ngRepeat in compiled by $compile does not work
问题描述
我需要动态编译HTML和功能将它作为文本。
所以,我有这个code(简本用于调试目的):
I need to dynamically compile html and pass it from function as text. So, I have this code (simplified version for debugging purpose):
angular.module('app', [])
.run(function($rootScope, $compile){
var data = ["1","2"];
var html =
'<div>' +
'<ul>' +
'<li ng-repeat="score in data">{{score}}</li>' +
'</ul>'+
'</div>';
var el = angular.element(html);
$rootScope.data = data;
var result = $compile(el)($rootScope);
console.log(result.html());
})
结果是唯一的:
<ul><!-- ngRepeat: score in data --></ul>
所以,它看起来像ngRepeat不重复,礼元素。
So, it looks like ngRepeat does not "repeat" "li" element.
为什么?
的jsfiddle: http://jsfiddle.net/yoorek/K4Cmk/
JsFiddle: http://jsfiddle.net/yoorek/K4Cmk/
(我知道DOM操作应在指令等等,我知道如何做到这一点其他的方式,但我需要了解为什么这不工作)
(I know DOM manipulation should be in directive etc. and I know how to do it other way but I need to understand why this does not work)
推荐答案
如果你看一下角度源$ C $ C,ngRepeat将操作DOM和$ watchCollection处理程序中重复的元素:
If you look at the angular source code, ngRepeat will manipulate the DOM and "repeat" the elements within the $watchCollection handler:
当你手动编译和运行块链接元素,为您的元素$表处理程序已经建立,但$消化阶段还没有发生。它是$消化阶段,其中范围检查所有的手表$ EX pressions和执行其相应的手表处理器。
When you manually compile and link the element from the run block, the $watch handlers for your element have been set up but the $digest phase has not happened yet. It is the $digest phase where the scope examines all of the $watch expressions and executes their corresponding watch handlers.
如果您想检查$摘要(渲染)阶段后,该元素可以使用$超时:
If you want to inspect the element after the $digest (render) phase you can use $timeout:
$timeout(function() {
console.log(el.html());
alert(el.html());
});
这篇关于ngRepeat由$编译编译不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!