Skip to content

Instantly share code, notes, and snippets.

@ocReaper
Last active January 27, 2016 07:44
Show Gist options
  • Save ocReaper/865517851213690547dc to your computer and use it in GitHub Desktop.
Save ocReaper/865517851213690547dc to your computer and use it in GitHub Desktop.
How to promisify ui-router state changes
// create the deferred variable
var stateChanged = $q.defer();
// hook our functionality to its promise
stateChanged
.promise
.then(function () {
// scroll to the desired element via ngSmoothScroll
var element = document.getElementById(next);
smoothScroll(element);
});
// if we're on the desired state, just resolve the variable
if ($state.is('somewhere')) {
stateChanged.resolve();
return;
}
// otherwise go to the state
$state.go('somewhere');
// hook to success for resolve
$rootScope.$on('$stateChangeSuccess', function () {
// anonymous function is required, due to adding it inline causes errors
stateChanged.resolve();
});
// hook to error for reject
$rootScope.$on('$stateChangeError', function () {
// anonymous function is required, due to adding it inline causes errors
stateChanged.reject();
});
@ocReaper
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment