15

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();
                });
            }
        };
    }
])
0

2 Answers 2

38

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;       
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

There is one more issue, templates = obj.getTemplates(); doesn't work due to the async. You may change the getTemplates to return a promise and then ... you know that :)
6

How about this?

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

        var templates = [];

        var some_object =  {

            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 = some_object.getTemplates();
                    });
            }

        };
        return some_object  

    }
])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.