Created
June 26, 2013 14:18
-
-
Save jakemmarsh/5867727 to your computer and use it in GitHub Desktop.
AngularJS directive to create a functional "back" button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.directive('backButton', function(){ | |
return { | |
restrict: 'A', | |
link: function(scope, element, attrs) { | |
element.bind('click', goBack); | |
function goBack() { | |
history.back(); | |
scope.$apply(); | |
} | |
} | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<a href back-button>back</a> |
But Back button still displayed in Main page. How to hide it
Why not use something like $localStorage (ngStorage) to save the previous state. That way it is preserved on reload.
In the run block...
Initialize storage
$localStorage.$default({
prevState:{}
});
Save previous state on state change:
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
if (from.name) {
$localStorage.prevState = {'state':from,'params':fromParams};
}
});
In the directive
Check storage for previous navigation and simply use state.go with the values from storage. I would probably also have a default page to go to, just in case...
angular.module("directive.backbutton",[])
.directive("backButton", ['$state','$localStorage', function ($state,$localStorage) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', goBack);
function goBack() {
if ($localStorage.prevState.state !== undefined) {
$state.go($localStorage.prevState.state,$localStorage.prevState.params);
}
}
}
}
}]);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!!