Question: I am using the [Angular UI bootstrap modal dialog](http://angular-ui.github.io/bootstrap/#/modal) and create it within a service:

```
myApp.factory('ModalService', ['$modal', function($modal) {
    return {
        trigger: function(template) {
            $modal.open({
                templateUrl: template,
                size: 'lg',
                controller: function($scope, $modalInstance) {
                    $scope.ok = function() {
                        $modalInstance.close($scope.selected.item);
                    };
                    $scope.cancel = function() {
                        $modalInstance.dismiss('cancel');
                    };
                }
            });
        },
        close: function() {
            // this should close all modal instances
        }
    };
}]);

```

How can I close all modal instances when calling `ModalService.close()` from a controller or whatsoever?

Answer: 
I added the below line to prevent browser back button routing and closing the popup. We need to inject $modalStack into angular controller.

```
event.preventDefault();
            $modalStack.dismissAll('close');

```
This is how i got it working in my project without using any factory or additional code.

```
  //hide any open $mdDialog modals
  angular.element('.modal-dialog').hide();
  //hide any open bootstrap modals
  angular.element('.inmodal').hide();
  //hide any sweet alert modals
  angular.element('.sweet-alert').hide();

```

I have a timeout function that emits logout as `$rootScope.$emit('logout');` and the listener in my service is as follows:

```
$rootScope.$on('logout', function () {
                    //hide any open $mdDialog modals
                    angular.element('.modal-dialog').hide();
                    //hide any open bootstrap modals
                    angular.element('.inmodal').hide();
                    //hide any sweet alert modals
                    angular.element('.sweet-alert').hide();

                    //do something else here  

                });

```

I don't know if this is the right approach , but it works for me.