我能够根据您使用顶级自定义 pre 指令的想法解决它,但使用不同的 impl:我正在运行 BFS 算法,每个摘要循环我尝试编译任何直接子 pre-包括。每次迭代我都会等到包含子项计数为零,然后再检查是否需要另一个循环(使用 scope.$watch)。完成后,我编译整个 my-pre 以解析任何 {{xxxx}} 并将其转换为 pre。 Working plunkr
// simulate a 3d party highligther (tested with HLJS)
.directive('myHighlighter', function($compile, $timeout) {
return {
restrict: 'E',
controller: function() {},
link: function(scope, element, attrs, controller) {
// wait for the end of the digest:
$timeout(function() {
$(element).replaceWith($('<pre>' + element.text() + '</pre>'));
});
}
}
})
// myPre will conert itself to the custom highlighter once done compiling:
.directive('myPre', function($compile, $timeout) {
return {
restrict: 'E',
controller: function() {},
link: {
pre: function(scope, element, attrs, controller) {
// limit the total inclusions allowed to avoid loops:
scope.it = 100;
// count inclusions:
scope.incCount = 0;
scope.$watch('incCount', function(newVal, oldVal, scope) {
if (oldVal !== newVal && newVal === 0) {
// watch the include tag count. When it's zero,
// see if we need another BFS pass for sub-children:
var children = $('pre-include', element).length;
if (children !== 0) {
$compile(element)(scope);
} else {
// If not, build the highlighter and we're done:
var e2 = $('<my-highlighter>' + element.html() + '</my-highlighter>');
$(element).replaceWith(e2);
$compile(e2)(scope);
}
}
});
},
post: function(scope, element, attrs, controller) {
}
}
}
})
.directive('preInclude', function($templateRequest, $compile) {
return {
link: {
pre: function(scope, element, attrs, myPre) {
scope.incCount++;
},
post: function(scope, element, attrs, myPre, transclude) {
scope.it--;
if (scope.it <= 0) {
console.log("max iterations reached, stopping");
return;
}
// enqueue the inclusion in the BFS queue:
$templateRequest(attrs.src).then(function(data) {
element.replaceWith(data);
scope.incCount--;
});
}
}
};
})