Reputation: 24385
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?
Upvotes: 8
Views: 8507
Reputation: 7563
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
Upvotes: 32