gpt4 book ai didi

angularjs - Angular JS : Detect if ng-bind-html finished loading then highlight code syntax

转载 作者:行者123 更新时间:2023-12-02 23:09:40 26 4
gpt4 key购买 nike

我正在使用 ng-bind-html 来绑定(bind)从数据库获取的数据。

<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);
});
});
});

当数据显示在屏幕上时,我要运行

$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});

用于高亮数据中的代码语法但不高亮。 (我使用 highlight library in CKEditor 来突出显示代码语法)

如果我在1秒后延迟加载突出显示代码,它会起作用,但我认为这不是一个好的解决方案

setTimeout(function () {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}, 1000);

我认为突出显示代码可能在 ng-bind-html 完成之前运行。

===更新
正如有人推荐的那样,我使用延迟时间为 0 的 $timeout 。但是,有时当网络较慢且页面加载较慢时,代码不会突出显示。

$scope.myHTML = response.data.content;
$timeout(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}, 0);

最佳答案

这就是指令非常有用的地方。为什么不自己附加 HTML 然后运行荧光笔?

模板:

<div ng-model="myHTML" highlight></div>

指令:

.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);
});

}
};
}
]);

示例:http://plnkr.co/edit/ZbcNgfl6xL2QDDqL9cKc?p=preview

关于angularjs - Angular JS : Detect if ng-bind-html finished loading then highlight code syntax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com