Search code examples
javascriptangularjsservicecontrollerinstance

Pass current controller instance to modal service


I have a CartController, which, on showCheckout, does this:

    ModalService.showModal({
        templateUrl: '/Product/CartCheckout',
        controller: 'CartController'
}).then(function (modal) {
        ...
    });

This is based on angularModalService.js. I'm just passing the current controller because I wouldn't like to create a new controller just to handle the Open() and Close() of the modal dialog.

However, passing a controller just by name seems to instantiate a new instance of that controller. I want to pass the current instance of my controller to the service. I've tried:

   controller: $controller('CartController', $scope)

But I get Unknown provider: $scopeProvider <- $scope <- CartController. I've also tried:

  controller: $scope.ctrl

But it just seems to be ignored without throwing any errors, nothing happens and the dialog is never shown.


Solution

  • I've fixed it by modifying AngularModalService.js as follows:

    var modalScope = $rootScope.$new();
    

    to

    var modalScope = options.controllerScope || $rootScope.$new();
    

    And then calling it as:

            ModalService.showModal({
                templateUrl: '/Product/CartCheckout',
                controller: 'CartController',
                controllerScope : $scope