Close Angular modal from different controller

1k Views Asked by At

I am new to Angular (I have to edit a project after my former colleague).

I have defined FormController and ModalController. ModalController is defined like this:

angular.module('app', [...]).controller('ModalController', ['part', class {
    constructor(part) {
       this.part = part;
    }
}]);

And in FormController I have following code to open modal:

openModal(template, part) {
    this.$uibModal.open({
        animation: true,
        templateUrl: template + '.html',
        controller: 'ModalController',
        controllerAs: 'ModalCtrl',
        resolve: {
            part: () => {
                return something;
            }
        }
    });
}

My problem is to close modal (after click on button in view).

3

There are 3 best solutions below

2
On BEST ANSWER

You will need to inject the dependency $uibModalInstance into the Modal's controller.

Then you can use either $dismiss or $close as shown in this example taken from UI Bootstrap Docs:

  $ctrl.ok = function () {
    $uibModalInstance.close($ctrl.selected.item);
  };

  $ctrl.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };

Since you controller is instantiated as part you would use that and presuming you don't need to pass a result or reason you can remove those params from the methods too:

  part.ok = function () {
    $uibModalInstance.close();
  };

  part.cancel = function () {
    $uibModalInstance.dismiss();
  };

Also a note if you see something prefixed $uib being used that means it is a part of the Angular UI Bootstrap component, hopefully that knowledge should help with the search for any more info you need in the future.

0
On

You have to inject the instance of uib-modal into the controller of modal which contain the close method. which you can use to close the modal.

openModal(template, part) {
    var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: template + '.html',
        controller: 'ModalController',
        controllerAs: 'ModalCtrl',
        resolve: {
            part: () => {
                return something;
            }
        }
    });
}

Inject modalInstance into the modal controller and then you can use

modalInstance .close()

method to close the modal.

0
On

You can pass the modal instance into the controller this way:

angular.module('app', [...]).controller('ModalController', ['part', '$uibModalInstance', class {
    constructor(part, $uibModalInstance) {
       this.part = part;
    }
}]);

And as Callum has put it, use the dismiss() and close() functions of $uibModalInstance to close the modal instance.