javascriptangularjsbootstrap-ui

Close Angular modal from different controller


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).


Solution

  • 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.