Pha*_*inh 5 syntax-highlighting angularjs ng-bind-html
我ng-bind-html
用于绑定从数据库获取的数据。
<p ng-bind-html="myHTML"></p>
app.controller('customersCtrl', function($scope, $http, $stateParams) {
console.log($stateParams.id);
$http.get("api link"+$stateParams.id)
.then(function(response) {
$scope.myHTML = response.data.content;
// this will highlight the code syntax
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
});
Run Code Online (Sandbox Code Playgroud)
当数据显示在屏幕上时,我要运行
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
Run Code Online (Sandbox Code Playgroud)
突出显示数据中的代码语法,但不突出显示。(我在CKEditor中使用高亮库来突出显示代码语法)
如果我在1秒后延迟加载高亮代码,它会起作用,但我认为这不是一个好的解决方案
setTimeout(function () {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}, 1000);
Run Code Online (Sandbox Code Playgroud)
我认为也许突出显示代码在ng-bind-html
完成之前运行。
===
更新
我$timeout
按照某些人的建议使用延迟时间0。但是, 有时在网络速度慢且页面加载速度慢的时候,代码不会突出显示。
$scope.myHTML = response.data.content;
$timeout(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}, 0);
Run Code Online (Sandbox Code Playgroud)
这是指令非常方便的地方。为什么不自己添加HTML,然后运行荧光笔?
模板:
<div ng-model="myHTML" highlight></div>
Run Code Online (Sandbox Code Playgroud)
指示:
.directive('highlight', [
function () {
return {
replace: false,
scope: {
'ngModel': '='
},
link: function (scope, element) {
element.html(scope.ngModel);
var items = element[0].querySelectorAll('code,pre');
angular.forEach(items, function (item) {
hljs.highlightBlock(item);
});
}
};
}
]);
Run Code Online (Sandbox Code Playgroud)
示例:http://plnkr.co/edit/ZbcNgfl6xL2QDDqL9cKc?p = preview
归档时间: |
|
查看次数: |
2779 次 |
最近记录: |