angularjs getting previous route path

Gihan picture Gihan · Mar 2, 2013 · Viewed 106.5k times · Source
<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.

Answer

andersh picture andersh · Sep 19, 2013

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);
    };

});