Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular-ui: Is any modal opened?

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
    });
like image 409
Sergei Panfilov Avatar asked Jun 09 '15 05:06

Sergei Panfilov


1 Answers

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

like image 59
dfsq Avatar answered Sep 19 '22 05:09

dfsq