Question

I have made this alertModal function on the $rootScope of my AngularJS app. It works nicely, however, I need each modal to overwrite subsequent modals. In other words, if there is already a modal open, I want any subsequent modals to close the existing. I can't figure out how to do that since each $modal instance creates a child scope on $rootScope. There is an option in $modal to pass it a scope to use (instead of $rootScope) but I'm not sure how to instantiate a custom scope purely for this purpose. Any help or clues would be great.

$rootScope.modalAlert = function (alert_type, message, acknowledge) {
    return $modal.open({
        templateUrl: '/partials/modals/alert.html',
        controller: AlertModalInstanceCtrl,
        resolve: {
            data: function () {
                return {
                    type: alert_type,
                    message: message,
                    acknowledge: acknowledge || false
                }
            }
        }
    })
}

var AlertModalInstanceCtrl = function ($scope, $modalInstance, data) {

    var heading = ''

    switch (data.type) {
        case 'error':
            heading = 'Oops'
            break
        case 'working':
            heading = 'Working'
            break
    }

    $scope.alert = {
        type: data.type,
        heading: heading,
        message: data.message,
        acknowledge: data.acknowledge
    }

    $scope.cancel = function () {
        $modalInstance.dismiss('cancelled');
    };
}

Not so relevant, but here is the accompanying HTML template:

<div class="row">
    <div class="col-sm-12">
        <h2 class="modal-header">{{ alert.heading }}</h2>

        <div class="modal-body">
            <div style="text-align: center;">
                <i ng-class="{
                'fa fa-exclamation-triangle fa-5x danger': alert.type=='error',
                'fa fa-info fa-5x info': alert.type=='working'
                }"></i>

                <p>{{ alert.message }}</p>
            </div>
            <button ng-show="alert.acknowledge" class="btn btn-default pull-right" ng-click="cancel()">Ok</button>
        </div>
    </div>
</div>
Was it helpful?

Solution

Looks like a good use case for $broadcast:

$rootScope.modalAlert = function (alert_type, message, acknowledge) {
     $rootScope.$broadcast('modal:start-open');
     return $modal.open({ 
     ...

And then in your controller:

var AlertModalInstanceCtrl = function ($scope, $modalInstance, data) {
    $scope.$on('modal:start-open', function() { 
        $modalInstance.dismiss('cancelled'); 
    });
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top