我有一个带有作用域的 AngularJS 应用程序。在这个范围内有一组内容对象,通过 View 显示。在 View 中,对于每个内容,都有一个按钮选择,连接到对象的方法 selectToggle()。
调用此方法时,将创建一个 $resource,它将向 API 发布一些信息。 在 $resource.query 回调中,我需要访问父 Content 对象,但由于它是异步的,所以我丢失了引用(“this”未指向 Window 对象)。
如何在回调函数中传递对创建 $resource 的对象的引用?
谢谢
function Content (informations) {
this.selected = false;
this.spinnerEnabled = false;
this.error = null;
this.selectToggle = function () {
this.spinnerEnabled = true;
ContentResource = $resource(
'/en/api/content',
null,
{'query': {'method': 'POST', isArray: false}}
).query({
'type': this.type,
'extId': this.id
}, function (response) {
// Here this is pointing to Window, not to the Content object
// so the following set are useless.
if (response.status == "success") {
this.selected = ! this.selected;
} else if (response.status == "error") {
this.error = response.message;
} else {
this.error = "Request failed";
}
this.spinnerEnabled = false;
});
};
}
最佳答案
您可以这样存储对 Content
对象的引用:
function Content (informations) {
this.selected = false;
this.spinnerEnabled = false;
this.error = null;
var self = this; // <-- Store reference for use later
// ...
然后,在你的回调中你可以引用self
:
if (response.status == "success") {
self.selected = ! self.selected;
} else if (response.status == "error") {
self.error = response.message;
关于javascript - 如何将对父对象的引用传递给 AngularJS $resource 查询回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21240410/