Angular JS:检测ng-bind-html是否完成加载,然后突出显示代码语法

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)

iH8*_*iH8 5

这是指令非常方便的地方。为什么不自己添加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

  • 这似乎是实现此功能(比超时)更专业的方法。基本上,这种逻辑应放在指令内部。关于这一点,有一点需要注意:您应该考虑将ngModel重命名为其他名称,因为当前实现建议它需要ngModel并为您提供ngModel的其他功能(这是不正确的)。 (2认同)