title: AgularJS: How to close active $modal on session timeout
body: <p>I'm developing a SPA, on session timeout i will redirect the user to login page. Here is my implementation</p>
  
  <pre><code>.run(['$rootScope', '$state', '$location', function ($rootScope, $state, $location) {
  
      $rootScope.$watch(function detectIdle() {
  
      var now = new Date();
  
       if (now - lastDigestRun &gt; 20 * 60 * 1000) {
  
          $location.path('/login');
  
          setTimeout(function () {
            alert("Your session has expired. Please log in again");
          }, 1000); 
       }
     });
  
  }])
  </code></pre>
  
  <p>Problem: If application timeouts when some $modal is open, page redirect to login page but $modal will not close.</p>
  
  <p>please help me to solve the problem</p>
  
  <p>Thanks</p>
  
  <p><strong>Update: Sorry for answering my own question, Working Solution given below:</strong></p>
  
  <pre><code> .run(['$rootScope', '$state', '$location', function ($rootScope, $state, $location) {
  
      var isSessionTimeout = false; 
  
      $rootScope.$watch(function detectIdle() {
  
      var now = new Date();
  
       if (now - lastDigestRun &gt; 20 * 60 * 1000) {
  
          isSessionTimeout = true;
          $location.path('/login');
  
          setTimeout(function () {
            alert("Your session has expired. Please log in again");
          }, 1000); 
       }
     });
  
    $rootScope.$on('$stateChangeSuccess', function () {
      if (isSessionTimedOut) {
          $modalStack.dismissAll();
      }             
   });
  
  }])
  </code></pre>