我是否必须将我的 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();
});
}
};
}
])
最佳答案
通过做 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;
}]);
关于function - AngularJS : From a factory, 如何调用另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18234442/