问题
I'm trying to get the initial html template for the ng-repeat directive that is used inside my custom directive which trancludes nested content. But instead the actual html text that was set inside the directive I get either already compiled ng-repeat directive or simply a comment that looks like the following:
<!-- ngRepeat: item in items -->
I already asked that question at github, but unfortunately the answer wasn't very clear for me. Is there a way to get ng-repeat directive template before it gets compiled?
Here's a simple example of what I am trying to achieve (and a plnkr):
app.directive('parent', function() {
return {
restrict:'E',
template:'<div ng-transclude></div>',
transclude: true,
priority: 1001,
scope: true,
compile: function(element, attrs) {
console.log(element.html());
console.log(element);
}
};
});
<parent>
<div ng-repeat="item in items">
{{item}}
</div>
</parent>
回答1:
ng-repeat directive has `transclude: "element", and so, when it is compiled, the entire element is taken out of DOM (in preparation for transclusion) and a comment is left.
So, the first console.log(element.html()) won't see anything, since the transclusion of your own directive hasn't happened.
But even if you examine the inner HTML at link-time, the ngRepeat will have been compiled, but its transclusion would not yet happen; it happens later, when scope.$watchCollection of ngRepeat fires.
So, the only way to see the content is to preempt the compilation of ngRepeat. You can either make your parent directive terminal: true, examine the contents and manually re-compile.
You can also add a directive that runs on a repeatable element with higher priority than ngRepeat and get the contents.
(You could even reuse the "ngRepeat" name)
app.directive("ngRepeat", function(){
return {
require: "?^parent", // optionally require your parent
priority: 1010,
compile: function(tElem){
var template = tElem.html();
return function link(scope, element, attrs, ctrls){
var parentCtrl = ctrls;
if (!parentCtrl) return;
// hand it off to the parent controller
parentCtrl.setTemplate(template);
}
}
}
})
Demo
来源:https://stackoverflow.com/questions/31890510/angularjs-how-to-get-ng-repeat-directive-template-before-it-gets-compiled