Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs UI bootstrap temporarily change URL on open and revert to original URL on close

I want to temporarily change the browser url when the ui bootstrap modal is opened ( The page behind should remain as is, only the url changes ). When the modal is closed the url should be reverted back to the original one.

Steps :

  1. User loads the page
    • url : xyz.com/home
  2. User clicks a link opens a modal
    • url : xyz.com/detail/123
    • possible solution : changing url with html5 push state
    • problem : Angular ui-router tries to run its routes as per the changed url, eventually changing the background page.
  3. User closes the modal
    • url : xyz.com/home
    • possible solution : html5 pop state
    • problem : Reloads the background page, which kills the purpose

Example implementation : Pinterest pins and their pin details popup.

like image 449
Kunal Dethe Avatar asked Nov 09 '22 14:11

Kunal Dethe


1 Answers

You can use ui-router-extras sticky state to solve your problem. There is simple example with modal by the link. You should create two named views, one for main content (background) and one for modal.

<div ui-view="app"></div>
<div ui-view="modal"></div>

Mark the state, from what you want to access to modal as sticky: true in route definition.

.state('main', {
  abstract: true,
  url: '/',
  templateUrl: '_layout.html'
})
.state('main.index', {
  url: '',
  sticky: true,
  views: {
    'app': {
      templateUrl: 'index.html'
    }
  }
})
.state('main.login', {
  url: 'login/',
  views: {
    'modal': {
      templateUrl: 'login.html'
    }
  }
})

Also add an event for stateChangeSuccess:

$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
  if ((from.views && !from.views.modal) || !from.views) {
    $rootScope.from = from;
    $rootScope.fromParams = fromParams;
  }
});

so, when you need to close modal, you can just

$state.go($rootScope.from, $rootScope.fromParams);

There is small problem for that solution. If you reload page on the modal state, then the app ui-view will be empty.

like image 76
E. Abrakov Avatar answered Nov 15 '22 12:11

E. Abrakov