diff --git a/src/state.js b/src/state.js index 4e6633fa7..6fb074a56 100644 --- a/src/state.js +++ b/src/state.js @@ -469,6 +469,8 @@ function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $ params: {}, current: root.self, $current: root, + previous: undefined, + previousParams: undefined, transition: null }; @@ -533,6 +535,32 @@ function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $ return this.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options)); }; + /** + * @ngdoc function + * @name ui.router.state.$state#back + * @methodOf ui.router.state.$state + * + * @description + * Convenience method for transitioning back to previous state. `$state.back` calls + * `$state.transitionTo` internally. + * + * @example + *
+     * var app = angular.module('app', ['ui.router.state']);
+     *
+     * app.controller('ctrl', function ($scope, $state) {
+     *   $scope.changeState = function () {
+     *     $state.back();
+     *   };
+     * });
+     * 
+ * + * @param {object} options If Object is passed, object is an options hash. + */ + $state.back = function (options) { + return this.transitionTo($state.previous, $state.previousParams, options); + }; + /** * @ngdoc function * @name ui.router.state.$state#transitionTo @@ -686,6 +714,8 @@ function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $ if ($state.transition !== transition) return TransitionSuperseded; // Update globals in $state + $state.previous = $state.current; + $state.previousParams = $state.params; $state.$current = to; $state.current = to.self; $state.params = toParams; diff --git a/test/stateSpec.js b/test/stateSpec.js index ce1ef3be7..630b65af0 100644 --- a/test/stateSpec.js +++ b/test/stateSpec.js @@ -483,6 +483,26 @@ describe('state', function () { })); }); + describe('.back()', function () { + it('transitions to previous state', inject(function ($state, $q) { + $state.transitionTo('about.person.item'); $q.flush(); + $state.go('^.^.sidebar'); $q.flush(); + $state.back(); $q.flush(); + + expect($state.$current.name).toBe('about.person.item'); + + })); + + it('transitions to previous state', inject(function ($state, $stateParams, $q) { + $state.transitionTo('about.person.item', { id:5 }); $q.flush(); + $state.go('^.^.sidebar'); $q.flush(); + $state.back(); $q.flush(); + + expect($stateParams).toEqual({ person: '', id: '5' }); + })); + + }); + describe('.reload()', function () { it('should reload the current state with the current parameters', inject(function ($state, $q, $timeout) { $state.transitionTo('resolveTimeout', { foo: "bar" });