Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS pass variable to service

I have this factory:

factory('getJson', ['$resource', function($resource) {
    return $resource('json/greetings.json', {}, {
      query: {method:'GET', isArray:true}
    });
  }]);

the file is hardcoded, 'greetings.json', and I want the factory to get files according to the checkboxes in my view:

<li><input type="checkbox" ng-model="includeVeggies" />Veggies</li>
<li><input type="checkbox" ng-model="includeGreetings" />Greetings</li>

Any idea how do I go about that?

like image 221
goldylucks Avatar asked Mar 19 '23 20:03

goldylucks


1 Answers

You can return a function:

.factory('getJson', ['$resource', function($resource) {
    return function (file) {
        return $resource(file, {}, {
            query: {method:'GET', isArray:true}
        });
    };
}]);

Then in your controller:

.controller('MyController', ['getJson', function (getJson) {
    getJson('json/greetings.json');
});

Here's a Plnkr.

like image 146
Danilo Valente Avatar answered Apr 08 '23 23:04

Danilo Valente