Reputation: 406
I'm showing and hiding a modal when the user go to a specific state (/login
), but I would keep the modal in background if the users goes to /register
from /login
.
If the user is in /login
and then goes to /register
, I would the login modal to stay opened, while if the user is in /login
and then goes to a different page, I would the login modal to disappear.
Actually I set the Angular-ui-router
$stateProvider
in this way:
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: "/",
templateUrl: "templates/home.html",
controller: 'HomeCtrl'
})
.state('login', {
url: "/login",
onEnter: function ($stateParams, $state, Modal) {
// * modalCtrl for Login
if (window.loginModal) {
window.loginModal.remove();
delete window.loginModal;
Modal.fromTemplateUrl('templates/user/login.html', function (modal) {
window.loginModal = modal;
loginModal.show();
});
} else {
Modal.fromTemplateUrl('templates/user/login.html', function (modal) {
window.loginModal = modal;
loginModal.show();
});
}
},
onExit: function ($stateParams, $state) {
if ( window.loginModal && /* condition like "!nextState.is('register')" */ ) {
window.loginModal.hide();
}
}
})
.state('register', {
url: "/register",
onEnter: function ($stateParams, $state, Modal, SlideBoxDelegate) {
// * modalCtrl for Register
if (window.registerModal) {
window.registerModal.remove();
delete window.registerModal;
Modal.fromTemplateUrl('templates/user/register.html', function (modal) {
window.registerModal = modal;
SlideBoxDelegate.update();
registerModal.show();
});
} else {
Modal.fromTemplateUrl('templates/user/register.html', function (modal) {
window.registerModal = modal;
SlideBoxDelegate.update();
registerModal.show();
});
}
},
onExit: function ($stateParams, $state) {
if ( window.registerModal ) {
window.registerModal.hide();
}
}
})
.state('not_found', {
url: "/not_found",
templateUrl: 'templates/not_found.html',
controller: 'NotFoundCtrl'
})
$urlRouterProvider.otherwise("/not_found");
$locationProvider.html5Mode(true);
})
Is there a way to set the condition like "!nextState.is('register')"
?
Thank you for reading :)
Upvotes: 4
Views: 4550
Reputation: 50392
The best trick I have found so far is to use the promise inside the $state service, in the onExit
function :
onExit: function ($state) {
$state.transition.then(toState => {
if (toState.name === 'nameOfTheWantedNextState') {
$state.go($state.current, {}, {reload: true});
}
})
}
This avoids listening to the event and storing the name somewhere, it only uses whats available at the time of the transition. Quite neat !
Upvotes: 2
Reputation: 5770
You can listen for $stateChangeStart
and note the value of the to
parameter some place that is accessible to your onExit
function, i.e. an injectable value or service.
In the future, there will be an injectable service that will represent the transition itself, which you'll be able to inspect and manipulate for things like this.
Upvotes: 2