AngularJS passes the variable to the service

I have this factory:

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

the file is hard-coded, 'greetings.json', and I want the factory to receive the files according to the flags in my view:

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

Any idea how to do this?

+4
source share
1 answer

You can return the 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 is the Plnkr .

+7
source

All Articles