public
Created

AngularJS directive to create a functional "back" button

  • Download Gist
directives.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
app.directive('backButton', function(){
return {
restrict: 'A',
 
link: function(scope, element, attrs) {
element.bind('click', goBack);
 
function goBack() {
history.back();
scope.$apply();
}
}
}
});
index.html
HTML
1
<a href back-button>back</a>

I am not sure I follow this. In a single page app, pressing the back button should take you to other "theoretical-pages" like Home, About Us, etc within the single-page app. What this does is take us back to previous window.href.

The problem here is that if the previous state is on another website, the user should not be redirected there. A solution is to track whether or not the user has a previous state within your Angular-powered app to decide whether or not to call history.back().

The way I implemented it was by tracking if the state changed within rootScope:

$rootScope.navigated = false;
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
    if (from.name) { $rootScope.navigated = true; }
}); 

Then you can evaluate it in your directive:

function goBack() {
if (scope.navigated) {
history.back();
scope.$apply();
}
}

Is there a way to back with the old state?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.