我正在创建一个允许用户创建预览 html 内容的 UI。
出于这个问题的目的,假设我有以下对象数组:
modules = [
{
id: 0,
type: 'title',
content: 'This is the title',
subtitle: 'This is the subtitle'
},
{
id: 1,
type: 'intro',
content: 'This is the <b>intro copy</b>. This is the intro copy!'
},
{
id: 2,
type: 'title',
content: 'This is the title'
}
];
我创建了一个指令,该指令循环遍历对象以根据类型选择模板并使用 $compile 来呈现不同的模块。
app.directive('module', function( $compile ){
// Define templates as strings
var titleTemplate = '<h1>' +
'{{ module.content }}' +
'</h1>' +
'<h3 ng-show="module.subtitle">{{ module.subtitle }}</h3>';
var introTemplate = '<p>' +
'{{ module.content }}' +
'</p>' +
'<p ng-show="module.secondContent"><em>{{ module.secondContent }}</em></p>';
// Select the current template by value passed in through scope.module.type
var getTemplate = function(moduleType) {
var template = '';
switch(moduleType) {
case 'title':
template = titleTemplate;
break;
case 'intro':
template = introTemplate;
break;
case 'ribbon':
template = ribbonTemplate;
}
return template;
};
// Pass the scope through to the template for access in the module
var linker = function( scope, element, attrs ) {
element.html( getTemplate( scope.module.type ) ).show();
$compile( element.contents() )( scope );
console.log(attrs);
};
return {
restrict: 'E',
link: linker,
replace: true,
scope: {
module : '='
}
}
});
最后,在我的 html 中
<module module="module" ng-repeat="module in modules"></module>
我遇到的问题是,当我在内容中有一个 html 元素时,例如<b>intro copy</b>
in modules[1].content
,该元素被呈现为一个字符串,而不是像预期的那样加粗文本。