如何在 angular material $mdDialog.confirm()/prompt() 中访问 class' 控制器变量?

How to access class' controller variable in angular material $mdDialog.confirm()/prompt()?

是否可以在用任一答案确认对话后更改 this.status

class ComponentCtrl {
    constructor($scope, $reactive, $mdDialog) {
        'ngInject';

        $reactive(this).attach($scope);
        this.$mdDialog = $mdDialog;

        this.status = "Click button below to set status";
    }

    showDialog(event) {
        this.$mdDialog.show(confirm).then(function() {
            // Yes
            console.log('I like dogs');
            this.status = 'I like dogs'; //doesn't work
        }, function() {
            // No
            console.log('I love cats');
            this.status = 'I love cats'; //doesn't work
        });
    }
}

解决方法是使用以下选项定义自定义对话框 (https://material.angularjs.org/latest/api/service/$mdDialog):

locals: { ParentCtrl: this },
bindToController: true

在上述情况下,您可以访问所有 variables/functions 父控制器,但它涉及更多编码,而不是使用 ngMaterial 的 shorthand 进行快速对话。

这里的技巧是使用this.$bindToContext

更多信息: http://www.angular-meteor.com/api/1.3.11/reactive-contexthttp://www.angular-meteor.com/tutorials/socially/angular1/handling-files-with-collectionfs - “20.15 处理文件选择”

class ComponentCtrl {
    constructor($scope, $reactive, $mdDialog) {
        'ngInject';

        $reactive(this).attach($scope);
        this.$mdDialog = $mdDialog;

        this.status = "Click button below to set status";
    }

    showDialog(event) {
        this.$mdDialog.show(confirm).then(this.$bindToContext(() => {
            // Yes
            console.log('I like dogs');
            this.status = 'I like dogs'; //working now
        }), this.$bindToContext(() => {
            // No
            console.log('I love cats');
            this.status = 'I love cats'; //working now
        }));
    }
}