P
P
PlasticMan2014-11-12 19:18:02
Angular
PlasticMan, 2014-11-12 19:18:02

Why does the [$rootScope:infdig] error fire when using $q in AngularJS?

Hello! There was a problem using the $q service in AngularJS.
Why is the $digest loop looping and throwing an error? Thanks in advance!
Here is the view:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <link rel="stylesheet" href="bower_components/bootstrap-css/css/bootstrap.css"/>
</head>
<body data-ng-app="AngularApp">

<div class="container" ng-controller="AngularController">
    {{tryDef()}}
</div>

<script src="bower_components/angular/angular.min.js"></script>
<script src="app/angular_app.js"></script>

</body>
</html>

Here is the Javascript itself:
(function () {
    var app = angular.module('AngularApp', []);

    app.factory('testDef', ['$q',function ($q) {
        return function (name) {

            var deferred = $q.defer();

            deferred.notify('About to greet ' + name + '.');

            var justTempValue = true;
            if (justTempValue) {
                deferred.resolve('Hello, ' + name + '!');
            } else {
                deferred.reject('Greeting ' + name + ' is not allowed.');
            }

            return deferred.promise;

        };
    }]);

    app.controller('AngularController', ['$scope', 'testDef', function ($scope, testDef) {

        //просто функция, что бы попробовать promises
        $scope.tryDef = function () {

            var promise = testDef('Robin Hood');
            promise.then(function(greeting) {
                console.log('Success: ' + greeting);
            }, function(reason) {
                console.log('Failed: ' + reason);
            }, function(update) {
                console.log('Got notification: ' + update);
            });

            return "5";
        };

    }]);

})();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2014-11-14
@lega

Your code started running for me, only here is the problem:
You have made the "{{tryDef()}}" binding, so the tryDef function is called at each iteration in $digest, and the tryDef function calls testDef where $q is created and executed .resolve which provokes a call to $digest. It turns out "an endless cycle".
You need to remove the testDef call to another function that is not called at each iteration in $digest, for example, make it call on click.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question