AngularJS : From a factory, how can I call another function

Purplefish32 picture Purplefish32 · Aug 14, 2013 · Viewed 18k times · Source

Do I have to move my getTemplates function out of the return or what ?

Example : I dont know what to replace "XXXXXXX" with (I have tried "this/self/templateFactory" etc... ) :

.factory('templateFactory', [
    '$http',
    function($http) {

        var templates = [];

        return {
            getTemplates : function () {
                $http
                    .get('../api/index.php/path/templates.json')
                    .success ( function (data) {
                        templates = data;
                    });
                return templates;
            },
            delete : function (id) {
                $http.delete('../api/index.php/path/templates/' + id + '.json')
                .success(function() {
                    templates = XXXXXXX.getTemplates();
                });
            }
        };
    }
])

Answer

AlwaysALearner picture AlwaysALearner · Aug 14, 2013

By doing templates = this.getTemplates(); you are referring to an object property that is not yet instantiated.

Instead you can gradually populate the object:

.factory('templateFactory', ['$http', function($http) {
    var templates = [];
    var obj = {};
    obj.getTemplates = function(){
        $http.get('../api/index.php/path/templates.json')
            .success ( function (data) {
                templates = data;
            });
        return templates;
    }
    obj.delete = function (id) {
        $http.delete('../api/index.php/path/templates/' + id + '.json')
            .success(function() {
                templates = obj.getTemplates();
            });
    }
    return obj;       
}]);