Search code examples
javascripthtmlangularjstwitter-bootstrapangular-directive

Why infinite digest error while compiling html text (from db) which contains a directive


  • I have a controller (say SampleController), in which it gets data (as following html text) from $http service & assigning it to $scope.htmlText

    <p>This is some content text
         <span class='sampleClassDirective' pid='1'>P1 Value</span> 
         some other text 
         <span class='sampleClassDirective' pid='2'>P2 Value</span> 
    some more text </p>
    
  • I want to render this html text in a view. As it is html text, I can use ng-html-bind directive to render the html-text as it is.

  • but i want to compile the html text, so that directives inside html text can get their templates if any

  • Actual problem starts here

  • As you can see above content has some tags with class="sampleClassDirective"
  • I have a directive with name as "sampleClassDirective"
  • This directive uses ui.bootstrap popover component in its template

    angular.module('app').dirctive('sampleClassDirective', 
        function(){
           return {
               restrict:'C',
               transclude:true,
               template:'<span uib-popover="This is pid">'+
                           '<ng-transclude></ng-transclude>'+
                        '</span>'
           }
        });
    
  • Now, I want to compile the whole htmlText which I got in sampleController, so that the "sampleClassDirective" & "uib-popover" both gets compiled.

  • So In view I gave

    <div id='htmlContent' ng-bind-html='render()'></div>
    
  • In sampleController

    $scope.render = function(){
        var elm = angular.element(htmlText);
        // compiling each directive
        var classDirectives = $(elm).find(".sampleClassDirective");
        for(var i=0, iMax=classDirectives.length; i<iMax; i++){
            $(elm).find(".sampleClassDirective")[i].append($compile(classDirectives[i])($scope));
        }
        // or can we compile all htmlText at once?
        // elm = $compile(elm)($scope)
    
        return $sce.trustAsHtml($(elm).html());
    }
    
  • **Question : **

  • While it is getting compiled, why I'm getting $rootScope infinite $digest error & it is aborting?

Solution

  • Putting an executed function on an an angular directive typically screws with the digest cycle. I would try putting the output of render on a different variable and adding that to ng-bind html, e.g

    $scope.renderedOutput = $scope.render();
    <div id='htmlContent' ng-bind-html='renderedOutput'></div>