Skip to content

Instantly share code, notes, and snippets.

@christopherthielen
Created March 26, 2018 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christopherthielen/babf6deebcd9a183dfecd37a03f75199 to your computer and use it in GitHub Desktop.
Save christopherthielen/babf6deebcd9a183dfecd37a03f75199 to your computer and use it in GitHub Desktop.
"use strict";
exports.__esModule = true;
var angular = require("angular");
var ngModule = angular.module('ct.ui.router.extras.previous', ['ct.ui.router.extras.core', 'ct.ui.router.extras.transition']);
function PreviousStateService($state, $q, $transitions) {
var previous = null;
var lastPrevious = null;
var memos = {};
$transitions.onStart({}, function ($transition$) {
var fromState = $transition$.from().$$state();
function commit() {
lastPrevious = null;
}
function revert() {
previous = lastPrevious;
}
if (fromState) {
lastPrevious = previous;
previous = {
state: $transition$.from(),
params: $transition$.params('from')
};
$transition$.promise.then(commit)['catch'](revert);
}
});
var $previousState = {
get: function (memoName) {
return memoName ? memos[memoName] : previous;
},
set: function (memoName, previousState, previousParams) {
memos[memoName] = { state: $state.get(previousState), params: previousParams };
},
go: function (memoName, options) {
var to = $previousState.get(memoName);
if (!to) {
return $q.reject(new Error('no previous state ' + (memoName ? 'for memo: ' + memoName : '')));
}
return $state.go(to.state, to.params, options);
},
memo: function (memoName, defaultStateName, defaultStateParams) {
memos[memoName] = previous || { state: $state.get(defaultStateName), params: defaultStateParams };
},
forget: function (memoName) {
if (memoName) {
delete memos[memoName];
}
else {
previous = undefined;
}
}
};
return $previousState;
}
PreviousStateService.$inject = ['$state', '$q', '$transitions'];
ngModule.service('$previousState', PreviousStateService);
ngModule.run(['$injector', function ($injector) {
// Inject $previousState so it initializes and registers hooks
$injector.get('$previousState');
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment