Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm kind of a noob to angularJS, as I just started the other day. I have a fairly simple question...

So say if I had multiple controllers that needs to pull data from one single JSON file, I would use a factory right? I sort of don't understand services/factory that well yet..

How exactly would you use a factory to pull data from a JSON file, to be used in multiple controllers?

Or do I just have this entire concept wrong?

share|improve this question
    
The angular documentation has a whole page dedicated to services. If you don't understand them after reading it, why would you understand them better after getting an answer here, since all you're basically asking is "I don't understand services, please explain them". Do you have a more specific question? Note that $http and $resource are two services already that allow getting data from a URL returning JSON. Wrapping them into a service can be useful sometimes, but is often useless. What have you tried? –  JB Nizet yesterday

1 Answer 1

up vote 0 down vote accepted

When using $http, you can pass a parameter which is to identify from where you're calling it. I use it something like this.

In my ctrl:

MyFactory.myMethod('this/is/path/to/file.php', 'getMyPosts', query);

In my factory, I have this:

.factory('MyFactory', ['$http', '$q', function($http, $q){

    return {
        myMethod: function(url, resourceType, query){
            return $http({
                method: 'GET',
                url: url,
                params: {
                    resourceType: resourceType,
                    query: query
                }
            }).then(
                function(response){
                    return response.data;
                }
            );

        }
    }

}]);

Now in your resource file (in my case it's a .php file), you can just check for some conditions:

$data = array();

if($_GET['resourceType'] == 'getMyPosts'){
    $data[] = add something to the $data array
}


echo json_encode($data);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.