3

I have a question: When I'm in a page I want return to previous page. I use the $routeProvider. How can I read the previous url?

I try to use this code in my controller but doesn't work...

angular.module.controller('myController', function($scope, $routeParams, $http, $location, $rootScope) { $rootScope.$on("$routeChangeSuccess", function (event, current, previous, rejection) { console.log(previous); $location.path('PREVIOUS PATH'); }); }); 

How can I read the previous path? Thanks!

1 Answer 1

3

I am not fully sure, what you want to achieve. So I would suggest, check this before you go your own way:

How to implement history.back() in angular.js

But, in case, you want to know how to keep the last state with angular and UI-Router, we can do it with a service. There is some naive implementation tracking just last state (not challenging the history.back())

Check the working example

Service definition:

.factory('PreviousState', ['$rootScope', '$state', function ($rootScope, $state) { var lastHref = "/home", lastStateName = "home", lastParams = {}; $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams , fromState, fromParams) { lastStateName = fromState.name; lastParams = fromParams; lastHref = $state.href(lastStateName, lastParams) }) return { getLastHref: function (){ return lastHref ; }, goToLastState: function (){ return $state.go(lastStateName, lastParams); }, } }]) 

So we just do listen the $stateChangeSuccess and keep the track of last state name and its $stateParams.

We can inject our service to all scopes:

.run(['$rootScope', 'PreviousState', function ($rootScope, PreviousState) { $rootScope.PreviousState = PreviousState; }]) 

And we can use it as a click or href:

<button ng-click="PreviousState.goToLastState()">go back</button> <a ng-href="#{{PreviousState.getLastHref()}}" > go to last href</a> 

Check that in action here

Sign up to request clarification or add additional context in comments.

1 Comment

I resolved with similar solution...I used $rootScope.$on('$locationChangeSuccess', function (evt, absNewUrl, absOldUrl) and so I can take the absOldUrl...Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.