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

后端 未结 2 1656
时光说笑
时光说笑 2021-01-04 03:29

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/templateFacto

相关标签:
2条回答
  • 2021-01-04 04:04

    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;       
    }]);
    
    0 讨论(0)
  • 2021-01-04 04:12

    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  
    
        }
    ])
    
    0 讨论(0)
提交回复
热议问题