angularjsangularjs-ng-route

Compare previous history route with current route in angular


Is it possible to get previous back hit route and compare with current route if the user were in current page before in angularjs ng-route? e.g If user is on list feed and click on item then hit default/site back button to current page, the current page will known he/she was here before.


Solution

  • You can implement your own routing history using $rootScope:

    $rootScope.$on('$locationChangeStart', function(ev, newUrl, oldUrl) {
        // Push previous Url into array.
        $rootScope.routes.push(oldUrl);
    });
    

    And then to compare with current route:

    $rootScope.$on('$locationChangeSuccess', function(ev, newUrl) {
        // Check if you've been here before.
        var visited = $rootScope.routes.indexOf(newUrl) !== -1;
    });
    

    Don't forget to inject $rootScope into your controllers:

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