Pedro4441
Pedro4441

Reputation: 261

Infinite loop with Angular expression binding with Ajax call

I am developing a basic Angular app which reads a feed.

I return in the index.html the value that the controller got clicking this button

<button ng-click="loadFeed()">Load News</button>

The problem is if I try to do just this:

{{loadFeed()}}

It goes into an infinitive loop.

Controllers.js:

myApp.controller("FeedCtrl", ['$scope','FeedService', function ($scope,Feed) {    
$scope.feedSrc = "http://rss.cnn.com/rss/cnn_topstories.rss";

$scope.loadFeed=function(){        
    Feed.parseFeed($scope.feedSrc).then(function(res){
        $scope.feeds=res.data.responseData.feed.entries;
    });

}
}]);

myApp.factory('FeedService',['$http',function($http){
return {
    parseFeed : function(url){
        return $http.jsonp('//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&callback=JSON_CALLBACK&q=' + encodeURIComponent(url));
    }
}
}]);

I am sorry, I am very new with AngularJS. I have seen another similar topic but I can't resolve my problem.

Upvotes: 0

Views: 755

Answers (1)

T.M.
T.M.

Reputation: 3221

When the first $digest cycle gets fired, your {{loadFeed()}} expression gets evaluated. This produces a call to your function parseFeed, which uses $http. Now, and here is the reason of your issue, the last thing Angular does in an ajax request through $http, is to call $rootScope.$apply(). This fires another $digest cycle, which causes your expression to be evaluated once again, which triggers another $rootScope.$apply(), and you can already see the infinite loop going on here.

Upvotes: 1

Related Questions