Reverend Dovie Reverend Dovie - 1 year ago 62
AngularJS Question

I'm stuck in infinite loop with app.factory - AngularJS

Ok, so I figured out WHY I'm stuck in a loop. I just don't know how to fix it.

I'm building a little app that grabs a JSON file off a third party server. This file contains the information of a user. For the sake of this exercise (I have an inkling of an idea why they did this, but it's killing me) I'm given a link to the JSON file. I finally figured out that the link I was given provides a different user's information each time you hit it!

So, I have the following:

app.factory('users', ['$http', function($http) {
return $http.get('link to file - can't give out actual link for proprietary reasons')

but when it goes to verify the JSON on the .apply(), it's changed, so it gets it again, and so on and so on.

How do I convince the code to get it once and be happy with it?

Answer Source

create a function which you can call from directive/controller and return it.

app.factory('users', ['$http', function($http) {
   function callExternalJson() {
       return $http.get('link to file - can't give out actual link for proprietary reasons') 

   return callExternalJson;

Factory Provider

Gives us the function's return value i.e. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory.