Search code examples
angularjsangular-meteorangularjs-material

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


Is it possible to change this.status after confirming dialog with either answer?

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
        });
    }
}

The way around is to define custom dialog (https://material.angularjs.org/latest/api/service/$mdDialog) with options:

locals: { ParentCtrl: this },
bindToController: true

In case above you can have access to all variables/functions of parent controller but it involves a lot more coding instead of using ngMaterial's shorthand for quick dialogs.


Solution

  • The trick here is to use this.$bindToContext.

    More info: http://www.angular-meteor.com/api/1.3.11/reactive-context and http://www.angular-meteor.com/tutorials/socially/angular1/handling-files-with-collectionfs - "20.15 Handle file selection"

    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
            }));
        }
    }