admin管理员组

文章数量:1131548

I have directive which is site header with back button and I want on click to go back to the previous page. How do I do it in the angular way?

I have tried:

<header class="title">
<a class="back" ng-class="icons"><img src="../media/icons/right_circular.png" ng-click="history.back()" /></a>
<h1>{{title}}</h1>
<a href="/home" class="home" ng-class="icons"><img src="../media/icons/53-house.png" /></a>   
</header>

and this is the directive js:

myApp.directive('siteHeader', function () {
    return {
        restrict: 'E',
        templateUrl: 'partials/siteHeader.html',
        scope: {
            title: '@title',
            icons: '@icons'
        }
    };
});

but nothing happens. I looked in the angular.js API about $location but didn't find anything about back button or history.back().

I have directive which is site header with back button and I want on click to go back to the previous page. How do I do it in the angular way?

I have tried:

<header class="title">
<a class="back" ng-class="icons"><img src="../media/icons/right_circular.png" ng-click="history.back()" /></a>
<h1>{{title}}</h1>
<a href="/home" class="home" ng-class="icons"><img src="../media/icons/53-house.png" /></a>   
</header>

and this is the directive js:

myApp.directive('siteHeader', function () {
    return {
        restrict: 'E',
        templateUrl: 'partials/siteHeader.html',
        scope: {
            title: '@title',
            icons: '@icons'
        }
    };
});

but nothing happens. I looked in the angular.js API about $location but didn't find anything about back button or history.back().

Share Improve this question edited Sep 10, 2015 at 17:40 pb2q 59.6k19 gold badges149 silver badges152 bronze badges asked Dec 28, 2012 at 13:29 baba-devbaba-dev 2,6326 gold badges29 silver badges33 bronze badges 2
  • 1 You mentioned that this worked for you. Does it take you to different pages within your app or just does the browser back? It looks like it does browser back to me. – user2537701 Commented Sep 20, 2013 at 0:00
  • If you have set AngularJS to use HTML5 mode, going to any page already in the browser's history will used the cached version and not reload it. The project I am working on uses a mixture of old and new code, and the previous page changes after the data is saved with AngularJS. It's not an option to upgrade the first page to use AngularJS so I had to load a third, non-AngularJS page to redirect back to the first one. Not a nice solution, but it works. – CJ Dennis Commented Nov 10, 2016 at 0:42
Add a comment  | 

10 Answers 10

Reset to default 266

You need to use a link function in your directive:

link: function(scope, element, attrs) {
     element.on('click', function() {
         $window.history.back();
     });
 }

See jsFiddle.

Angular routes watch the browser's location, so simply using window.history.back() on clicking something would work.

HTML:

<div class="nav-header" ng-click="doTheBack()">Reverse!</div>

JS:

$scope.doTheBack = function() {
  window.history.back();
};

I usually create a global function called '$back' on my app controller, which I usually put on the body tag.

angular.module('myApp').controller('AppCtrl', ['$scope', function($scope) {
  $scope.$back = function() { 
    window.history.back();
  };
}]);

Then anywhere in my app I can just do <a ng-click="$back()">Back</a>

(If you want it to be more testable, inject the $window service into your controller and use $window.history.back()).

Ideally use a simple directive to keep controllers free from redundant $window

app.directive('back', ['$window', function($window) {
        return {
            restrict: 'A',
            link: function (scope, elem, attrs) {
                elem.bind('click', function () {
                    $window.history.back();
                });
            }
        };
    }]);

Use like this:

<button back>Back</button>

Another nice and reusable solution is to create a directive like this:

app.directive( 'backButton', function() {
    return {
        restrict: 'A',
        link: function( scope, element, attrs ) {
            element.on( 'click', function () {
                history.back();
                scope.$apply();
            } );
        }
    };
} );

then just use it like this:

<a href back-button>back</a>

In case it is useful... I was hitting the "10 $digest() iterations reached. Aborting!" error when using $window.history.back(); with IE9 (works fine in other browsers of course).

I got it to work by using:

setTimeout(function() {
  $window.history.back();
},100);

Or you can simply use javascript code :

onClick="javascript:history.go(-1);"

Like:

<a class="back" ng-class="icons">
   <img src="../media/icons/right_circular.png" onClick="javascript:history.go(-1);" />
</a>

There was a syntax error. Try this and it should work:

directives.directive('backButton', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function () {
                history.back();
                scope.$apply();
            });
        }
    }
});

Angular 4:

/* typescript */
import { Location } from '@angular/common';
// ...

@Component({
  // ...
})
export class MyComponent {

  constructor(private location: Location) { } 

  goBack() {
    this.location.back(); // go back to previous location
  }
}

For me, my problem was I needed to navigate back and then transition to another state. So using $window.history.back() didn't work because for some reason the transition happened before history.back() occured so I had to wrap my transition in a timeout function like so.

$window.history.back();
setTimeout(function() {
  $state.transitionTo("tab.jobs"); }, 100);

This fixed my issue.

In AngularJS2 I found a new way, maybe is just the same thing but in this new version :

import {Router, RouteConfig, ROUTER_DIRECTIVES, Location} from 'angular2/router'; 

(...)

constructor(private _router: Router, private _location: Location) {}

onSubmit() {
    (...)
    self._location.back();
}

After my function, I can see that my application is going to the previous page usgin location from angular2/router.

https://angular.io/docs/ts/latest/api/common/index/Location-class.html

本文标签: javascriptHow to implement historyback() in angularjsStack Overflow