简体   繁体   中英

Closing an Angular Material dialog

Calling $mdDialog.cancel() from the controller will close the dialog. But is there a way of not using a controller to close the dialog box like directly from the html ? I want something like this to work:

<md-dialog-actions layout="row">
      <span flex></span>
      <md-button ng-click="$mdDialog.cancel()" style="margin-right:20px;" >
        Ok
      </md-button>
    </md-dialog-actions>

In your show() code, you can create a child scope and add the close() function:

$mdDialog.show({
    ...
    scope: angular.extend($scope.$new(), { close: function() {$mdDialog.cancel();} })
});

Then in your dialog's HTML, just use ng-click="close()" .

Alternatively, you can pass the $mdDialog object as a property of your scope.

However, it's even more code than creating a controller (which can also be created inside the show() function).

Simply

<md-button ng-click="cancel()"></md-button>

And in your dialog controller

$scope.cancel = function() {
    $mdDialog.cancel();
}

You can add mat-dialog-close to the button you want to trigger the close event from

Example: <button mat-dialog-close> Close </button>

You can bind an scope into the dialog config:

 $mdDialog.show({ targetEvent: $event, template: '<md-dialog>' + ' <md-dialog-content>Hello {{ employee }}!</md-dialog-content>' + ' <md-dialog-actions>' + ' <md-button ng-click="closeDialog()" class="md-primary">' + ' Close Greeting' + ' </md-button>' + ' </md-dialog-actions>' + '</md-dialog>', scope: $scope, preserveScope: true });

For more info about the config properties you can see the dialog config documentation in here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM