I am using ng-bind-html
for binding data that I get from database.
<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);
});
});
});
When the data displayed on the screen, I want to run
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
for highlight the code syntax in the data but it is not highlight. (I use highlight library in CKEditor for highlight the code syntax)
And if I delay load the highlight code after 1s, it will work but I think it is not a good solution
setTimeout(function () {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}, 1000);
I think maybe the highlight code run before ng-bind-html
finished.
===
UPDATE
I am using $timeout
with delay time 0 as some person recommend. However, sometime when the network is slow and the page load slow, the code will not highlighted .
$scope.myHTML = response.data.content;
$timeout(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}, 0);
$timeout
instead ofsetTimeout
;$timeout
is a wrapper that ensures that a$digest
is processed. you may not even need to have a 1sec delay in that instance, just the amount of time it takes for the$digest
to process. – Derna$timeout
automatically issues a$digest
(which redraws the UI) and then performs the logic inside, instead of waiting for a static amount of time. – Derna$timeout
and$digest
for do it. – Pile