I'm using Angular Material within my project. I use many dialogs (just for alert purposes), but I now require quite a complex dialog.
This is the example that the Angular Material site uses:
function showDialog($event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
parent: parentEl,
targetEvent: $event,
template: '<md-dialog aria-label="List dialog">' +
' <md-dialog-content>' +
' <md-list>' +
' <md-list-item ng-repeat="item in items">' +
' <p>Number {{item}}</p>' +
' ' +
' </md-list-item></md-list>' +
' </md-dialog-content>' +
' <md-dialog-actions>' +
' <md-button ng-click="closeDialog()" class="md-primary">' +
' Close Dialog' +
' </md-button>' +
' </md-dialog-actions>' +
'</md-dialog>',
locals: {
items: $scope.items
},
controller: DialogController
});
function DialogController($scope, $mdDialog, items) {
$scope.items = items;
$scope.closeDialog = function() {
$mdDialog.hide();
}
}
}
Instead, would be it possible to not reference a controller
for the $mdDialog
, and to just allow it to use the same controller where it was called from?
For example, if it is called via this button, the dialog would simply use the MyCtrl
controller so that the dialog can access the scope variables.
<div ng-controller="MyCtrl">
<md-button ng-click="showDialog($event)" class="md-raised">
Custom Dialog
</md-button>
</div>
Is this a possibility? Or must I continually use the locals
property along with broadcasting to keep passing variables back and forth?
In order to use the dialog component, we need to import the MatDialogModule module into the app module like this. import { MatDialogModule } from '@angular/material/dialog'; After importing the dialog module, the next step is to include it inside the imports array as given below.
The MatDialogRef provides a handle on the opened dialog. It can be used to close the dialog and to receive notifications when the dialog has been closed. Any notification Observables will complete when the dialog closes.
Approach: First we need to import 'MatDialog' from '@angular/material/dialog' and we need to create an instance for it in the constructor. Using this instance we can open the dialog box component. Now create a separate component for the dialog and write code as per the requirements.
You can do that if you use controllerAs
. I am doing it with es6 like that:
this.$mdDialog.show({
targetEvent: event,
templateUrl: 'path/to/my/template.html',
controller: () => this,
controllerAs: 'ctrl'
});
Without es6 it will look like this:
.controller('AppCtrl', function($scope, $mdDialog, $mdMedia) {
var self = this;
this.showTabDialog = function(ev) {
$mdDialog.show({
controller: function () {
return self;
},
controllerAs: 'ctrl',
templateUrl: 'tabDialog.tmpl.html',
});
};
});
I modified the basic usage example from the docs: http://codepen.io/kuhnroyal/pen/gPvdPp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With