AngularJS:从工厂,我怎么称呼另一个功能

时间:2013-08-14 14:26:16

标签: function angularjs factory

我是否必须将getTemplates函数移出返回或什么?

示例:我不知道用什么替换“XXXXXXX”(我试过“this / self / templateFactory”等等):

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

2 个答案:

答案 0 :(得分:37)

通过执行templates = this.getTemplates();,您指的是尚未实例化的对象属性。

相反,您可以逐渐填充对象:

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

答案 1 :(得分:6)

这个怎么样?

.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  

    }
])