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

前端之家收集整理的这篇文章主要介绍了angularjs – Angular JS:检测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);
        });
    });
});

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

$('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完成之前运行的高亮代码.

===
UPDATE
我正在使用$timeout,延迟时间为0,因为有人推荐.但是,有时当网络速度较慢且页面加载速度较慢时,代码将不会突出显示.

$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相关文章