还不能对答案发表评论,但我发现这种技术很有用。
如果您“手动”加载模板并将文本插入 dom,Angular 会自动将内容转换为 HTML 实体,这意味着您的原始模板仍然可读,但可以正确显示。
在我的应用程序中,我使用 $sce 和 $templateRequest 来获取模板,然后将一个角度模板变量设置为获取的模板的值。
几点注意事项:
- 每个指令实例有多个代码示例,由 codeType 变量标识
- 我的模板文件名采用 _{codeType}.sample 的形式,例如 _css.sample
- 模板位置作为 dom 中指令的属性传入
- dom 元素容器由类 .sample-{codeType} 标识,例如 .sample-css
- 角度占位符由 {{sample{codeType}} 标识,例如 {{samplecss}}
- 为了防止出现竞争条件,我使用 $timeout 等待一个节拍并允许当前的 $apply() 在代码上调用 Prism 之前完成。
此方法还允许具有相似输出的多种类型的代码 - 例如,在我的样式指南中,我同时显示了输出 HTML (codeType = 'html') 和未渲染的 Angular 模板 (codeType = 'ng') - 两者都需要Prism .language-markup 类。
如果每个指令只有一个代码示例,这可以大大简化。
function StyleGuideComponentController($scope, $element, $templateRequest, $sce, $timeout)
{
var codeSampleTypes =
[
'html',
'ng',
'ngjs',
'css',
'less'
];
insertAllCodeSamples();
function insertAllCodeSamples()
{
var key;
for (key in codeSampleTypes)
{
insertCodeSample(codeSampleTypes[key]);
}
}
function insertCodeSample(codeType)
{
var sampleUrl = $scope.templateLocation + '/_' + codeType + '.sample',
sampleCode = $sce.getTrustedResourceUrl(sampleUrl);
$templateRequest(sampleCode).then(function(template)
{
var codeElement = $element.find('.sample-' + codeType)[0],
prismLanguage = codeType,
prismLanguageTypes =
{
'html' : 'markup',
'ng' : 'markup',
'js' : 'javascript',
'ngjs' : 'javascript'
},
key;
for (key in prismLanguageTypes)
{
if (prismLanguage === key)
{
prismLanguage = prismLanguageTypes[key];
}
}
codeElement.className += ' language-' + prismLanguage;
$scope['sample' + codeType] = template;
$timeout(function()
{
Prism.highlightElement(codeElement);
});
}, function()
{
$scope['sample' + codeType] = 'An error occurred' +
' while fetching the code sample';
});
}
return {
restrict : 'E',
scope :
{
templateLocation: '='
},
controller : StyleGuideComponentController
};
}