Plnkr 演示 http://plnkr.co/edit/uGGM8iWLgOfyAH4DB9Cm?p=preview
您可以利用 Angular 的模板引擎来构建自己的实时模板编辑器,并包含自定义代码标签。
HTML
<h3>Text Editor</h3>
<textarea ng-model="model"></textarea>
<h3>Raw Preview</h3>
<div>
{{ model }}
</div>
<h3>Live Preview</h3>
<js-code-content model="model">
Loading...
</js-code-content>
定制指令
app.directive('jsCodeContent', function($compile) {
return {
restrict: 'E',
scope: {
model: '=model'
},
link: function(scope, element, attr) {
scope.$watch('model', function(value, oldValue) {
var model = value || '';
// encode HTML
model = angular.element('<div></div>').text(model).html();
model = model.replace(/\[js:bold\]/g, '<js-bold>');
model = model.replace(/\[\/js:bold\]/g, '</js-bold>');
model = model.replace(/\[js:italic\]/g, '<js-italic>');
model = model.replace(/\[\/js:italic\]/g, '</js-italic>');
model = model.replace(/\[js:code\]/g, '<js-code>');
model = model.replace(/\[\/js:code\]/g, '</js-code>');
model = model.replace(/\[js:hilight\]/g, '<js-hilight>');
model = model.replace(/\[\/js:hilight\]/g, '</js-hilight>');
var e = angular.element('<content></content>');
e.html(model);
element.empty();
element.append(e);
$compile(e)(scope);
});
}
}
});
JS 代码模板
app.directive('jsCode', function() {
return {
restrict: 'E',
transclude: true,
template: '<code ng-transclude></code>'
}
})
app.directive('jsBold', function() {
return {
restrict: 'E',
transclude: true,
template: '<b ng-transclude></b>'
}
})
app.directive('jsItalic', function() {
return {
restrict: 'E',
transclude: true,
template: '<i ng-transclude></i>'
}
})
app.directive('jsHilight', function() {
return {
restrict: 'E',
transclude: true,
template: '<span class="highlight" ng-transclude></span>'
}
})