为什么我得到$ digest()迭代?如何跟踪递归脚本的活动?

时间:2014-11-28 13:13:39

标签: javascript angularjs counter watch

我试图理解我的递归脚本,它效率低下。

我尝试创建计数器,告诉我它被调用了多少次,从哪里开始,所以我可以更好地理解它的行为。但是,我在控制台中遇到错误,它会超载它可以调用的迭代次数:

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: function (context) {\n          for(var i = 0, ii = length, part; i<ii; i++) {\n            if (typeof (part = parts[i]) == 'function') {\n  .........

经过大量阅读后,我强烈认为它与Angular每次更新计数器时重新计算一切,$watch视为一个变化,引发新的$digest轮。这是对的吗?

如果是这样,我如何在递归脚本上实现计数器?

为了提供一个与我想要做的非常类似的示例,我按ganarajpr分叉了一个JSFiddle并添加到here: JSFiddle

正如Stackoverflow所要求的那样,代码在下面复制:

HTML:

<div ng-app="myApp">
<div ng-controller="MainCtrl">
<script type="text/ng-template"  id="tree_item_renderer.html">
    {{incrementCounter()}}
    {{data.name}}
    <button class="btn btn-primary" ng-click="add(data)">Add node</button>
    <button class="btn btn-primary" ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
    <ul>
        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
    </ul>
</script>

<ul ng-app="Application" ng-controller="TreeController">
    <li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>

</ul>
    <h3> Counter {{counter}}</h3>
</div>

</div>

使用Javascript:

var app = angular.module("myApp", []);
app.controller("MainCtrl", ['$scope', function ($scope) {
    $scope.counter = 0;
    $scope.incrementCounter = function () {
        console.log("Increment called");
        $scope.counter++;
        document.counter++;
    }
}]);
app.controller("TreeController", ['$scope', function ($scope) {

    $scope.delete = function (data) {
        data.nodes = [];
    };
    $scope.add = function (data) {
        var post = data.nodes.length + 1;
        var newName = data.name + '-' + post;
        data.nodes.push({
            name: newName,
            nodes: []
        });
    };
    $scope.tree = [{
        name: "Node",
        nodes: []
    }];
}]);

1 个答案:

答案 0 :(得分:2)

$digest周期内,{{incrementCounter()}}导致{{counter}}导致$digest更改导致新的{{incrementCounter()}}周期,从而无限期地评估$digest无限期。基本上如果你有一个每$watch个周期增加一个计数器,你就不能让这个变量影响任何{{counter}} ed表达式的结果。

您需要替代$watch而不依赖{{1}}表达式的结果(例如直接写入元素)。