S Panfilov
S Panfilov

Reputation: 17531

How to close modal after transition to another modal on angular ui router

I'm using angular ui router to open modals.

I have two states with modals:

  1. 'modal.first'
  2. 'modal.second'

What I want is to close the first modal by button click and change state to 'modal.second'.

The problem is that i can only close modal or change state (but first modal still open).

Here state definitions:

$stateProvider
    .state('modal.first', {
        url: '/first',
        onEnter: function ($state, $modal) {
            $modal.open({
                templateUrl: 'some_url',
                controller: 'FirstCtrl',
                resolve: {
                    //...
                }
                            }
            }).result.finally(function () {
                $state.go('^');
            });
        }
    })

The second modal definition is all the same (with state name modal.second and url /second).

I'm trying to close modal (and change state) like this:

(FirstController)

$scope.goSecond = function () {
    $state.go('modal.second', $stateParams);
    $modalInstance.close();
};

But this didn't work. I able to choose only one - or $state.go(...), or $modalInstance.close().

I think maybe i should take more attention to the .finally() block. But still have no ideas. Thanks.

Link to the official FAQ with modals: click

UPDATE I cannot just change state in finally without any statements, because I'm need to change state only by clicking the button (and make .go('^') in any other cases).

Upvotes: 0

Views: 1026

Answers (1)

milanlempera
milanlempera

Reputation: 2263

You can define service, which hold modalInstance and close it if is open called again.

angular.module('someModule')
  .service("singleModal", function($modal) {
    this.modalInstance = null;
    this.open = function(options) {
      if (this.modalInstance) {
        this.modalInstance.close();
      }

      this.modalInstance = $modal.open(options);
      return this.modalInstance;
    };
  })

You can see simple example of service (without ui bootstrap) here

Upvotes: 3

Related Questions