Angular Infinite $digest Loop Angular Infinite $digest Loop angularjs angularjs

Angular Infinite $digest Loop


The problem that you were having was that you were setting a field on the scope, which implicitly calls $digest and lays out the template again. But, laying out the template makes the http request again, and then changes the scope, which calls $digest. And that is the infinite loop.

You can avoid this by ensuring that the http request never gets triggered during a layout of the template.

A more angular correct way of implementing your app would be to extract your GET request into a proper service and then injecting your service into the controller.

Then in the controller, you make the service call, like this:

app.controller('resultController', ['$scope', '$routeParams', 'whatsitService',    function($scope, $routeParams, $http) {        $scope.result = $routeParams.query;        whatsitService.doit().then(function(result) {            $scope.whatsit = result;        }    });

Your template would look like this:

<h1>{{ result }}</h1><p>{{ result }} is a {{ whatsit }}</p>


The problem is you trying to call a function and publish the return value directly and the value that you are trying to return is out of scope. You need to put that value in scope.

Code snippet:

app.controller('resultController', ['$scope', '$routeParams', '$http',function($scope, $routeParams, $http) {    $scope.result = $routeParams.query;    $scope.itIsA = "";    $scope.whatIsIt = function() {        $http.get('json/foods.json').success(function(data) {            var lists = JSON.parse(data);            var itIsA = 'uuggghhhhh';            if (lists['fruit'].contains($scope.result)) {                $scope.itIsA = 'fruit';            } else if (lists['vegetable'].contains($scope.result)) {                $scope.itIsA = 'vegetable';            }                       });    }}]);

and in the HTML Template:

p>{{ result }} is a {{itIsA}}</p>


Infinite $digest Loop can happen in this below case if you have bound an expression to it like : {{events()}}

and

$scope.events = function() { return Recording.getEvents();}

But not in the below case. even if you have bound {{events}}

$scope.events = Recording.getEvents();

The reason is in the first angular suppose the value is changing in every digest loop and it keeps updating it. In second one it simply wait for the promise.