0

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.

3
  • An issue might be that loadFeed() does not return anything. Nothing to display. Maybe put {{feeds}}, and call $scope.loadFeed() in your controller to initialize the data. Commented Mar 28, 2014 at 15:47
  • Thank you very much for your answer, but I dont get it sorry. feeds is only filled inside loadFeed right now, so I cant call it before calling loadFeed, where do you mean to call $scope.loadFeed()? Commented Mar 28, 2014 at 16:08
  • Maybe what you are looking for is ng-init? What happens if you do {{loadFeed()}} is that it gets called on every digest cycle, which will make it freak out at you. ng-init="loadFeed()" in your button would call it once, and the {{feeds}} would be populated. Commented Mar 28, 2014 at 16:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the explanation. With this in mind, what worked for me was the ng-init that Zack Argyle said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.