Angular-ui: Is any modal opened?

607 views Asked by At

I'm want to launch a code if any modal opens. Commonly I'm want something like:

    $scope.$watch(function () {
            return $modal.isOpenState;
        }, function (val) {
            //my code here
        }, true
    );

But I'm didn't know what to watch. Yes, I can detect open event for each instance, like:

modalInstance.opened.then(function() {
    //my code here
});

But this isn't DRY.

P.S. Also I'm can make something like $('.modal').hasClass('in') in $watch function, but this is little bit ugly

P.P.S And btw I'm using ui-router to open modals (see faq here)

    $modal.open({
        templateUrl: "...",
        resolve: {...  },
        controller: function($scope) { ... }
    }).result.finally(function() {
        //can put code here, but same issue
    });
1

There are 1 answers

3
dfsq On BEST ANSWER

There is an internal service UI modal uses called $modalStack. This service is used by $modal and has method called getTop to retrieve currently opened modal instance. So you can inject this service and simply watch getTop result on $rootScope. For example:

app.run(function($rootScope, $modalStack) {
    $rootScope.$watch($modalStack.getTop, function(newVal, oldVal) {
        if (newVal) {
            console.log('opened', newVal, oldVal);
        }
    });
});

Demo: http://plnkr.co/edit/ZVD0cryL0qXNGl9UPMxB?p=preview