How to implement history.back() in angular.js

前端 未结 10 1636
南笙
南笙 2020-11-27 09:37

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:

相关标签:
10条回答
  • 2020-11-27 10:36

    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
      }
    }
    
    0 讨论(0)
  • 2020-11-27 10:38

    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.

    0 讨论(0)
  • 2020-11-27 10:40

    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();
                });
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-27 10:42

    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>
    
    0 讨论(0)
提交回复
热议问题