javascript - 如何将对父对象的引用传递给 AngularJS $resource 查询回调函数?

标签 javascript angularjs

我有一个带有作用域的 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/

相关文章:

javascript - 异步加载的 SVG-Filter feColorMatrix 在 Chrome 中工作,而不是在 Safari 或 Firefox 中工作

javascript - 刷新 Node.js 页面

javascript - 使用 $timeout 与 lodash_.debounce 基准的 Angular native 去抖动

javascript - React-native-ui-lib 是否可用于 React Native 0.60? (安卓X)

javascript - 将图像数据存储在 cookie 中

javascript - AngularJS:访问服务中的动态基本 href 值

AngularJS复选框不起作用

c# - 使用 HttpCookie 超时/url 过期

javascript - angularjs 表单按钮未验证或未启用

angularjs - 使用 AngularJS,如何一次将所有表单字段设置为 $dirty?