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: 
Inject the `$modalStack` service and call the function `$modalStack.dismissAll()`, see the code on [GitHub](https://github.com/angular-ui/bootstrap/blob/master/src/modal/modal.js#L287) for details:

```
myApp.factory('ModalService', ['$modal', '$modalStack' function($modal, $modalStack) {
    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(reason) {
            $modalStack.dismissAll(reason);
        }
    };
}]);

```
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');

```