使用$ mdDialog

时间:2017-06-22 04:45:18

标签: angularjs angular-material angular-components mddialog

我使用角度1.6.2和角度材料1.1.4。这是我用于$ mdDialog的组件:

class CommentReplySettingsController {
  /** @ngInject */
  constructor($mdDialog, $log) {
    this.$mdDialog = $mdDialog;
    $log.log(this.settingType);
  }

  hideDialog() {
    this.$mdDialog.hide();
  }

  cancelDialog() {
    this.$mdDialog.cancel();
  }
}

export const commentReplySettings = {
  template: require('./comment-reply-settings.html'),
  bindings: {
    settingType: '<'
  },
  controller: CommentReplySettingsController
};

以上内容将转换为如下组件:

import angular from 'angular';

import {commentReplySettings} from './comment-reply-settings';

export const commentReplySettingsModule = 'commentReplySettings';

angular
  .module(commentReplySettingsModule, [])
  .component('app.user.commentReplySettings', commentReplySettings);

这是另一个组件的控制器功能,我在$ mdDialog中使用上面的组件:

  showCommentReplySettingDialog(ev) {
    this.settingType = 'global';
    this.$mdDialog.show({
      template: '<app.user.comment-reply-settings class="md-dialog-container" setting-type="$ctrl.settingType"></app.user.comment-reply-settings>',
      parent: angular.element(this.$document.body),
      autoWrap: false,
      targetEvent: ev,
      clickOutsideToClose: true,
      fullscreen: true
    });
  }

问题是 CommentReplySettingsController 中的 this.settingType 始终未定义。如何让这个工作?

修改:如果我在 CommentReplySettingsController 中使用 settingType: '@' 并执行 setting-type="global" 在上面的 showCommentReplySettingDialog 函数中,正确设置了settingType绑定中的值。使用内部模板时,似乎 $ ctrl 未定义。有什么原因吗?

1 个答案:

答案 0 :(得分:1)

问题是在$ctrl内引用$scope,因此,当我使用scope: this.$scope时,它的效果非常好:

const _this = this;
this.settingType = 'global';
this.$mdDialog.show({
  template: '<app.user.comment-reply-settings class="md-dialog-container" setting-type="$ctrl.settingType"></app.user.comment-reply-settings>',
  parent: angular.element(this.$document.body),
  autoWrap: false,
  scope: _this.$scope,
  targetEvent: ev,
  clickOutsideToClose: true,
  fullscreen: true
});

但仍然需要通过$scope似乎有点荒谬。如果没有$scope的其他解决方案,请发送。