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

后端 未结 3 1968
陌清茗
陌清茗 2021-01-13 11:00

I am using ng-bind-html for binding data that I get from database.

app.controller(\'customersC
相关标签:
3条回答
  • 2021-01-13 11:31

    So here's what is happening:

    1. You update the $scope.myHTML value
    2. You run your jQuery each() loop
    3. The digest cycle runs and your template is updated

    Notice that the digest cycle runs after your jQuery each() loop -- or, more specifically, after your $http callback function is finished running.

    That means the value of $scope.myHTML in your controller is not applied to the ng-bind-html directive until after your loop has already finished.

    To overcome this, you could use Angular's $timeout service instead of the native browser setTimeout() method. By default, $timeout will invoke the callback function during the next digest cycle, which means it will run after the changes to $scope.myHTML are applied to the ng-bind-html directive (as long as you update $scope.myHTML before calling $timeout()).

    Working example: JSFiddle

    0 讨论(0)
  • 2021-01-13 11:42

    as you know the statements execute asynchronously, if there is no timeout $('pre code') will be empty as the DOM is still not rendered. use $timeout instead of setTimeout for the same.

    0 讨论(0)
  • 2021-01-13 11:50

    This is where directives come in very handy. Why not append the HTML yourself and then run the highlighter?

    Template:

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

    Directive:

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

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

    0 讨论(0)
提交回复
热议问题