jcubic jcubic - 4 months ago 37
Javascript Question

Can't set property of controller in angular material modal dialog

I'm using Angular 1.5 with ES6 and webpack, my code is as follow:

export default class HomeController {
static $inject = ['$mdDialog', '$sce'];

constructor($mdDialog, $sce) {
this.$mdDialog = $mdDialog;
this.tasks = [
{
label: "<strong>Something strong</strong>",
id: 10
}
];
this.tasks = this.tasks.map(function(item) {
item.label = $sce.trustAsHtml(item.label);
return item;
});
}

showRejectionDialog(ev, $index) {
this.task = this.tasks[$index];
this.index = $index;
console.log(this.task);
console.log(this.index);
this.$mdDialog.show({
controller: HomeController,
preserveScope: true,
controllerAs: 'vm',
template: require('./rejectionDialogModal.jade'),
parent: angular.element(document.body),
targetEvent: ev,
});
}
allow($index) {
this.tasks[$index].status = 'CONFIRMED';
}
reject(index) {
this.$mdDialog.hide();
console.log(index);
console.log(this.task);
console.log(this.index);
//this.tasks[this.index].status = 'REJECTED';
}
cancel() {
this.$mdDialog.cancel();
}
}


and rejectionDialogModal.jade look like this:

md-dialog(aria-label='Reject', ng-cloak='')
form(name="rejectionForm")
md-dialog-content
.md-dialog-content
h2.md-title Reject confirmation for
div {{vm.task|json}}
span(ng-bind-html="vm.task.label")
textarea(placeholder="Please provide a reason for rejection", style="width: 530px; height: 75px")
md-dialog-actions(layout="row")
span(flex)
md-button(ng-click="vm.cancel()") CANCEL
md-button.md-primary.md-raised(ng-click="vm.reject(vm.index)") REJECT


the console.log inside showRejectionDialog show the correct values but the one from reject show undefined, also vm.task is undefined inside dialog and label is not displayed. How can I pass properties to modal dialog when I use the same controller?

Answer

Try this one to create a controller function that has access the $scope

showRejectionDialog(ev, $index) {
    this.task = this.tasks[$index];
    this.index = $index;
    console.log(this.task);
    console.log(this.index);
    this.$mdDialog.show({
        controller: function () {
             this.parent = $scope;
        },
      preserveScope: true,
      controllerAs: 'vm',
      template: require('./rejectionDialogModal.jade'),
      parent: angular.element(document.body),
      targetEvent: ev,
    });        
  }