Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-bind-html gives an infinite digest error ($rootScope.infdig)

Tags:

angularjs

If I use a function with the regular ng-bind, everything seems to be fine. But if I were to use ng-bind-html, I receive the infinite digest error.

=== View ===
1. <span ng-bind="test()">
2. <span ng-bind-html="test()">

=== Controller ===
1. $scope.test = function() {
       return 1;
   }  

2. myapp.controller('myapp', function($scope, $sce) {
    $scope.test = function() {
        return $sce.trustAsHtml('<input></input>');
    }
});

Any idea what's going on here? The view does render the input, but throws that infinite error digest error. The documentation isn't very helpful either.

like image 527
john smith Avatar asked Oct 14 '13 21:10

john smith


1 Answers

The problem is that when your ng-bind-html is evaluated, Angular calls your test function and gets the result of $sce.trustAsHtml('<input></input>'). Angular then evaluates all of the bindings again to see if everything has settled. This means it once again calls your test function, and sees if the return value matches the old value. Unfortunately, it does not. This is because the values return from $sce.trustAsHtml are not comparable via ===.

Try this as proof:

console.log($sce.trustAsHtml('<input></input>') === $sce.trustAsHtml('<input></input>'));

That will print false. This means that each and everytime Angular calls your test function, it's returning a different value as far as it's concerned. It tries a number of times and then gives up.

If you instead bind the result of $sce.trustAsHtml into a scope variable rather than a function call, the problem goes away:

$scope.input = $sce.trustAsHtml('<input></input>');

<span ng-bind-html="input"></span>
like image 144
ksimons Avatar answered Oct 25 '22 07:10

ksimons