Pass current scope to modalInstance when using controllerAs syntax

半腔热情 提交于 2019-12-17 21:29:41

问题


I'm using controllerAs syntax to avoid a $scope soup in my controllers, and also using ui.bootstrap to present a modal view.

I need to open a modalInstace that shares the same scope as the current controller. When injecting the scope, you could probably do something like:

var modalInstance = $uibModal.open({
      templateUrl: 'addEditModal.html',
      scope: $scope
    });

However as I'm not injecting the scope, and using controllerAs syntax, that will not work.

From what I've found, you will need to use resolve to pass the data, but you have to pass it explicitly via functions. Is there a way to pass the entire scope?

There is a bunch of stuff I need to do in that modal and passing loads of data seems overkill.

Don't want to do this, as it seems messy...

var modalInstance = $modal.open({
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  resolve: {
    user: function() {
        return vm.user;
    },
    something: function() {
        return vm.something;
    },
    blah: function() {
        return blah;
    }
  }
});

Any better ideas?


回答1:


I need to open a modalInstace that shares the same scope as the current controller.

Modal service creates inherited scope. And

var modalInstance = $uibModal.open({
  templateUrl: 'addEditModal.html',
  scope: $scope
});

does not inject the scope but specifies parent scope for modal controller (otherwise root scope will be used as the parent).

Since controllerAs was used on parent controller, modal controller will have access to inherited vm object on its scope.




回答2:


Not sure If I understood correctly, but I got it working by passing/injecting the current 'controllerAs' in the resolve parameter

var modalInstance = $uibModal.open({
      templateUrl: 'addEditModal.html',
      controller: 'AudioItemAddEditCtrl as vm',
      resolve: {
        parent: function(){
            return vm
        }
    }
    });

And then, in the AudioItemAddEditCtrl...

var AudioItemAddEditCtrl = function(parent, AudioItemService, $ModalInstance) {
...
}

Then I'm able to use 'parent' to access the parent controller scope directly.

Hope this helps someone else.



来源:https://stackoverflow.com/questions/33164281/pass-current-scope-to-modalinstance-when-using-controlleras-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!