Search code examples
javascriptangularjsangularjs-resourceangularjs-factory

change variable in angularjs factory using $resource


In my AngularJS app I want a factory with a method to change a variable in the factory itself by using $resource. The code I have written so far is the following:

factories.factory('FooFactory', function ($resource) {
    var foo = null;
    return {
        query: function () {
            foo = $resource(baseUrl + '/someUrl/:query', {}, {
                query: { method: 'GET', isArray: true }
            });
        },
        getFoo: function () {
            return foo;
        }
    }
});

So when calling FooFactory.query({query: "someString"}); I want the factory to change the value of foo to the value received from the resource.

I need this behaviour because the value of foo is changed by a directive and I need to bind its value to a value in the scope of a controller.

However, the code above doesn't seem to work. What am I doing wrong?


Solution

  • You do not call any method of resource you only initialize it. Try this:

    factories.factory('FooFactory', function ($resource) {
        var foo = null;
        return {
            query: function () {
                foo = $resource(baseUrl + '/someUrl/:query', {}, {
                    query: { method: 'GET', isArray: true }
                }).query();
            },
            getFoo: function () {
                return foo;
            }
        }
    });