DJ22T
DJ22T

Reputation: 1640

Pass a timeout to angular bootstrap Modal

I'm trying to pass a timeout to a bootstrap modal in Angular JS, in order to show a couple of buttons and cancel that timeout if one of them is clicked

The scenario of what I'm trying to do: I have a sessión that expires in 3 minutes, so in 1.5 minutes I show that modal to the user prompting if he wants to extend the session, if he clicks "Ok", I cancel the timeout and call a function that reset the notification again.

If i try to pass it using the resolve that comes with the Modal, the modal launches just when the Timeout ends, (i guess this might be since it's a promise)

This doesn't has to be the solution but it's what i came up with, if anyone else has a better way or practice, I'll appreciate if you can share

Here is the plunker to see it

Code

JS

angular.module('app', ['ui.bootstrap'])
.controller('Main', MainCtrl);

MainCtrl.$inject = ['$modal', '$timeout'];
function MainCtrl($modal,$timeout) {
  var vm = this;

  vm.callModal = callModal;
  /*vm.people = [
    'Fred',
    'Jim',
    'Bob'
  ];*/
  vm.time = $timeout(function() { // Timeout 
    alert("timeout ended");
  }, 10000);

  function callModal() {
    $modal.open({
      templateUrl: 'modal.html',
      controller: ['$modalInstance', 'time', ModalCtrl],
      controllerAs: 'vm',
      resolve: {
        time: function () { return vm.time; }
      }
    });
  }
}

function ModalCtrl($modalInstance, time) {
  var vm = this;

  console.log(time);

}

Main

 <body ng-controller="Main as vm">
    <button type="button" class="btn btn-sm btn-primary" ng-click="vm.callModal()">Call modal</button>
 </body>

Modal

<div class="modal-header">
    <h3 class="modal-title">Modal title</h3>
</div>
<div class="modal-body">
    {{ vm.timeout }}
</div>
<div class="modal-footer">
    <button class="btn" ng-click="$close()">Cancel</button>
</div>

Upvotes: 2

Views: 3545

Answers (1)

Fernando Pinheiro
Fernando Pinheiro

Reputation: 1816

So you want to close the modal from outside.

Check this fork.

You have to setup the modal instance in your controller and close it after the timeout.

  vm.time = $timeout(function() { // Timeout 
    alert("timeout ended");
    if(vm.modal)
      vm.modal.dismiss('cancel')
  }, 10000);

  function callModal() {
    vm.modal = $modal.open({
      templateUrl: 'modal.html',
      controller: ['$modalInstance', ModalCtrl],
      controllerAs: 'vm'
    });
  }

Upvotes: 2

Related Questions