How to use the same controller with the Angular Material dialog box?

I am using Angular Material in my project. I use a lot of dialogs (for alert purposes only), but now I need a rather complicated dialog.

This is an example that uses the Angular Material site:

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, it would be possible not to reference the controller on $mdDialog and just let it use the same controller where it was called from?

For example, if it is called through this button, the dialog will simply use the MyCtrl controller MyCtrl that the dialog box can access the scope variables.

 <div ng-controller="MyCtrl"> <md-button ng-click="showDialog($event)" class="md-raised"> Custom Dialog </md-button> </div> 

Is it possible? Or should I constantly use the locals property along with the broadcast to keep the variables back and forth?

+8
javascript angularjs angular-material
source share
1 answer

You can do this if using controllerAs . I do this with es6 as follows:

 this.$mdDialog.show({ targetEvent: event, templateUrl: 'path/to/my/template.html', controller: () => this, controllerAs: 'ctrl' }); 

Without es6, it would 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 changed the basic usage example from the docs: http://codepen.io/kuhnroyal/pen/gPvdPp

+24
source share

All Articles