angularjs getting previous route path
Solution 1:
This alternative also provides a back function.
The template:
<a ng-click='back()'>Back</a>
The module:
myModule.run(function ($rootScope, $location) {
var history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
$location.path(prevUrl);
};
});
Solution 2:
Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:
$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
console.log('success', evt, absNewUrl, absOldUrl);
});
Solution 3:
In your html :
<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>
On your main controller :
$scope.go_back = function() {
$window.history.back();
};
When user click on Go Back link the controller function is called and it will go back to previous route.
Solution 4:
@andresh For me locationChangeSuccess worked instead of routeChangeSuccess.
//Go back to the previous stage with this back() call
var history = [];
$rootScope.$on('$locationChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
$location.path(prevUrl);
history = []; //Delete history array after going back
};