我正在尝试构建一个语法高亮指令。
基本上是这样的指令:
<div syntax-highlight="language">{{codeValue}}</div>应转化为:
<div syntax-highlight="language">
<pre><code>{{codeValue that has been syntax highlighted with span tags}}</code></pre>
</div>所以我要说的是
return {
scope: {
'syntaxHighlight': '@'
},
template: '<pre><code ng-transclude></code></pre>',
transclude: true,
link: function (scope, element, attributes, controller, transclude) {
}
};当该代码当前运行时,{{codeValue}}中的所有内容(基本上是一个字符串)在包装到span元素中时都会被放入span中。
这不太好,因为我不只是希望在code元素中有一个字符串。在被排除之前,我需要修改这个值。
我需要将这个{{codeValue}}传递到语法突出显示函数中,该函数将返回语法突出显示的代码,该代码将是原始的HTML (因此一个原始字符串(净化和转义)将被转换为带有span标记的HTML )。然后,这个原始的HTML需要放在code元素中。
我试过使用transclude函数,但内容似乎已经被屏蔽了。
发布于 2014-02-26 15:24:23
这就是我最后所做的:
['$sce', function($sce){
return {
scope: {
'syntaxLanguage': '@'
},
restrict: 'AE',
template: codeBlockTemplate,
transclude: true,
replace: true,
link: function (scope, element, attributes, controller, transclude) {
//transclude's clone is children elements of the directive element, it will wrap any unwrapped text nodes with the span tag
transclude(scope, function (clone) {
//get the directive element's content as text, this will be the {{code}}
var code = angular.element(clone).text();
//convert the code string into a highlighted code string
var highlightedCode = hljs.highlight(scope.syntaxLanguage, code, true);
//bind to the scope as trusted HTML
scope.highlightedCode = $sce.trustAsHtml(highlightedCode.value);
});
}
};
}]以此为模板:
<pre><code ng-bind-html="highlightedCode"></code></pre>发布于 2014-02-26 14:52:01
基本上,您想将CodeValue传递给指令并在链接函数中操作它?
那麽:
<syntaxhighlight codevalue="codeValue"> </syntaxhighlight>
return {
restrict: 'E',
scope: {'codevalue': '='},
template: '<div> <pre><code ><span>{{sanitizedText}}</span></code></pre></div> ',
replace: true,
link: function (scope, element, attributes, controller) {
scope.sanitizedText = textEditingFunction(scope.codevalue); //pass codevalue to the modifying function, who will return the sanitized text
}
};https://stackoverflow.com/questions/22043894
复制相似问题