<h1>{{header}}</h1> <!-- This Back button has multiple option --> <!-- In home page it will show menu --> <!-- In other views it will show back link --> <a ng-href="{{back.url}}">{{back.text}}</a> <div ng-view></div>
In my module config
$routeProvider. when('/', { controller:HomeCtrl, templateUrl:'home.html' }). when('/menu', { controller:MenuCtrl, templateUrl:'menu.html' }). when('/items', { controller:ItemsCtrl, templateUrl:'items.html' }). otherwise({ redirectto:'/' });
Controllers
function HomeCtrl($scope, $rootScope){ $rootScope.header = "Home"; $rootScope.back = {url:'#/menu', text:'Menu'}; } function MenuCtrl($scope, $rootScope){ $rootScope.header = "Menu"; $rootScope.back = {url:'#/', text:'Back'}; } function ItemsCtrl($scope, $rootScope){ $rootScope.header = "Items"; $rootScope.back = {url:'#/', text:'Back'}; }
As you can see in my controllers I have hard coded the back button url and text (Actually I don't need the text as using an image). In this way I found back button navigate incorrectly in some cases. I cannot use history.back()
coz my back button changes to a menu link in home view.
So my question is how do I get the previous route path in controllers or is better way to achieve this ?
I have created a Plunker demonstration of my problem. Please check that.
$route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location. url() and tries to map the path to an existing route definition.
Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application.
AngularJS was originally developed in 2009 by Miško Hevery at Brat Tech LLC as the software behind an online JSON storage service, that would have been priced by the megabyte, for easy-to-make applications for the enterprise.
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); }; });
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With