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

前端 未结 10 1689
南笙
南笙 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:18

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

    HTML:

    
    

    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 Back

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

提交回复
热议问题