如何将同一个控制器与 Angular Material 对话框一起使用?

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

我在我的项目中使用 Angular Material。我使用了很多对话框(只是为了提醒目的),但我现在需要一个相当复杂的对话框。

这是 Angular Material 站点使用的示例:

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();
    }
  }
}

相反,是否可以不为 $mdDialog 引用 controller,而只允许它使用调用它的同一控制器?

例如,如果通过此按钮调用,对话框将简单地使用 MyCtrl 控制器,以便对话框可以访问范围变量。

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

有这种可能吗?或者我必须不断地使用 locals 属性 和广播来保持来回传递变量吗?

如果您使用 controllerAs 就可以做到这一点。我是这样用 es6 做的:

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

如果没有 es6,它将看起来像这样:

.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',
        });
    };
});

我修改了文档中的基本用法示例: http://codepen.io/kuhnroyal/pen/gPvdPp