加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular JS:检测ng-bind-html是否完成加载然后突

发布时间:2020-12-17 17:53:55 所属栏目:安全 来源:网络整理
导读:我使用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) { $scop
我使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读