Using $compile in a directive triggers AngularJS infinite digest error

做~自己de王妃 提交于 2019-12-13 16:26:39

问题


Any thoughts on why this directive is triggering an infinite digest error?

http://jsfiddle.net/smithkl42/cwrgLd0L/13/

var App = angular.module('prettifyTest', []);
App.controller('myCtrl', function ($scope) {
    $scope.message = 'Hello, world!';
})

App.directive('prettify', ['$compile', function ($compile) {
    var template;
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            if (!template) {
                template = element.html();
            }
            scope.$watch(function () {
                var compiled = $compile(template)(scope);
                element.html('');
                element.append(compiled);
                var html = element.html();
                var prettified = prettyPrintOne(html);
                element.html(prettified);
            });
        }
    };
}]);

It seems to be the very first line in the scope.$watch() function that's triggering the model update, as when I remove that line, it doesn't trigger the error.

var compiled = $compile(template)(scope);

I'm a little confused as to why that line is triggering another $digest - it doesn't seem to be updating anything directly in the scope.

Is there a better way to accomplish what I'm trying to do, e.g., some other way to check to see if the key values in the scope have actually changed so I can recompile the template? (And is there a better way of grabbing the template?)


回答1:


When you use scope.$watch() with just a function and no watch expression, it registers a watcher that gets triggered on every digest cycle. Since you're calling $compile within that watcher, that's effectively triggering another digest cycle each time since it needs to process the watchers created by your template. This effectively creates your infinite digest cycle.

To use the same code, you should probably just be compiling once in your postLink function, but I don't think you even need to do that - you should be able just use the template property. Then your $watch() statement should include an expression targeting the property you want to watch for changes - in this case, just 'message', and update the HTML accordingly.



来源:https://stackoverflow.com/questions/27509934/using-compile-in-a-directive-triggers-angularjs-infinite-digest-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!