Dailycode.info

Short solution for short problems

AngularJS: Back Button

Something simple, though not yet default in Angular + $stateprovider.

How to go to the previous state?

Lots of posts, easy solution. The best one yet is to save the previous state in the state itself when a state change was succesfull.

Just add these 3 lines to your app.run:

$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
	$state.previous = fromState;
});

Now the previous state is already saved and can be accessed anywhere the state is injected:

$scope.goBackToProject = function () {
	console.log('Back to: '+$state.previous);
	$state.go($state.previous);
}

And just call it onclick:

<button ng-click="goBackToProject()" class="btn btn-danger" type="button"><span class="glyphicon glyphicon-step-backward"></span> Back</button>

That's it!