范围问题-基于类的控制器中的嵌套$ mdDialog

时间:2019-05-23 00:09:07

标签: javascript angularjs angularjs-scope es6-class angularjs-material

我正在将AngularJS控制器移至基于类的模型,以支持最近出现的一些较新的想法。这在使用AngularJS Materials $ mdDialog服务时出现了一个我遇到麻烦的问题。

我有一个设置,其中打开了一个父对话框,当用户想要撤消所做的任何更改时,另一个对话框将执行确认步骤。

父对话框代码:

// Expand item data
expandItem(data, ev){
  this._mdDialog.show({
    controller: 'expandCtrl',
    controllerAs: 'ec',
    templateUrl: 'path/to/template',
    parent: angular.element( document.body ),
    targetEvent: ev,
    clickOutsideToClose: true,
    locals: { 
      data: {
        asset: data,
        table: this.selectTable
      }}
  }).then(rowData => {
  }, function(){});
}

嵌套对话框代码:

(function () {
'use strict';
class expandCtrl {

  constructor($mdDialog, data) {
    this.itemData = data;
    this.itemStateCapture = angular.copy(this.itemData);
    this._mdDialog = $mdDialog;
  }

  // Cancel edits and revert item back to its previous state
  cancelEdits(ev) {

    let cancelConfirm = this._mdDialog.confirm()
    .multiple(true)
    .title('Are you sure?')
    .textContent('Really cancel all edits and revert this item back to its original state?')
    .ariaLabel('Edit cancel confirmation')
    .targetEvent(ev)
    .ok('Cancel Edits!')
    .cancel('Go Back');

    this._mdDialog.show(cancelConfirm).then(function() {

      //**************************//
      //**** The Problem Line ****//
      //**************************//
      this.itemData = this.itemStateCapture;

    }, function() {});
  }
}
// Init Controller
angular.module('dbProject').controller('expandCtrl', expandCtrl);

})();

我需要在 this._mdDialog.show()行内重写顶级 this.itemData 变量。不过似乎存在范围界定问题,并且我没有尝试成功地访问该变量。我曾尝试注入$ scope,重定向到外部函数,甚至通过angular.element()。controller()访问数据,但没有取得任何进展。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我最终将控制器转换为一种混合方法,包括$ scope。没有它,$ mdDialog似乎无法正常运行(尽管我很想被证明是错误的)。

参见下文:

(function () {
'use strict';
  angular
    .module('myProject')
    .controller('expandCtrl', expandCtrl);

    expandCtrl.$inject = [
      '$mdDialog',
      '$timeout',
      '$scope',
      'data',
      'uaService',
      'dataService'
    ];

    function expandCtrl($mdDialog, $timeout, $scope, data, uaService, dataService){
      // Submit edits functionality
      this.submitEdits = function(table, access, data, ev){
        let confirmSubmit = $mdDialog.confirm()
        .multiple(true)
        .title('Are you sure?')
        .textContent('Really submit these changes?')
        .ariaLabel('Submit confirmation')
        .targetEvent(ev)
        .ok('Submit!')
        .cancel('Go Back');

        $mdDialog.show(confirmSubmit).then(function() {

            let editData = {
                table: $scope.table,
                data: $scope.itemData,
                prevData: $scope.itemStateCapture
            }

            dataService.submitEdits(editData)
            .then(res =>{
                console.log(res);
            }).catch(e =>{console.error(e)})

        }, function() {});
    }
  }
})();