Do I have to move my getTemplates function out of the return or what ?
我是否必须将getTemplates函数移出返回或什么?
Example : I dont know what to replace "XXXXXXX" with (I have tried "this/self/templateFactory" etc... ) :
示例:我不知道用什么替换“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 个解决方案
#1
37
By doing templates = this.getTemplates();
you are referring to an object property that is not yet instantiated.
通过做templates = this.getTemplates();您指的是尚未实例化的对象属性。
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;
}]);
#2
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
}
])
#1
37
By doing templates = this.getTemplates();
you are referring to an object property that is not yet instantiated.
通过做templates = this.getTemplates();您指的是尚未实例化的对象属性。
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;
}]);
#2
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
}
])