AngularJS:从页面获取上一个URL(路径)

时间:2015-05-18 12:45:08

标签: angularjs angular-ui-router

我有一个问题:当我在某个页面时,我想返回上一页。我使用$routeProvider。我怎样才能阅读上一个网址?

我尝试在我的控制器中使用此代码但不起作用...

angular.module.controller('myController', 
  function($scope, $routeParams, $http, $location, $rootScope) {

    $rootScope.$on("$routeChangeSuccess", 
      function (event, current, previous, rejection) {

        console.log(previous);
        $location.path('PREVIOUS PATH');

    });
 });   

我如何阅读上一条路径?谢谢!

1 个答案:

答案 0 :(得分:3)

我不完全确定,你想要实现的目标。所以我建议,在你走自己的路之前检查一下:

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

但是,如果您想知道如何使用angular和UI-Router保持最后一个状态,我们可以使用服务来实现。有一些天真的实现跟踪最后状态(不挑战history.back())

检查working example

服务定义:

.factory('PreviousState', ['$rootScope', '$state',
  function ($rootScope, $state) {

    var lastHref = "/home",
        lastStateName = "home", 
        lastParams = {}; 

    $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams
                                                       , fromState, fromParams) {
      lastStateName = fromState.name;
      lastParams = fromParams;
      lastHref = $state.href(lastStateName, lastParams)  
    })

    return {
      getLastHref: function (){ return lastHref ; },
      goToLastState: function (){ return $state.go(lastStateName, lastParams); },
    }

}])

所以我们只听取$stateChangeSuccess并跟踪上一个state 名称及其 $stateParams

我们可以将服务注入所有范围:

.run(['$rootScope', 'PreviousState',
  function ($rootScope, PreviousState) {
    $rootScope.PreviousState = PreviousState;
}])

我们可以将它用作点击或href:

<button ng-click="PreviousState.goToLastState()">go back</button>
<a ng-href="#{{PreviousState.getLastHref()}}" > go to last href</a>

action here

中查看
相关问题