gpt4 book ai didi

AngularJS:从页面获取以前的网址(路径)

转载 作者:行者123 更新时间:2023-12-04 07:29:44 28 4
gpt4 key购买 nike

我有一个问题:当我在一个页面中时,我想返回到上一页。我使用 $routeProvider。如何读取之前的 url?

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

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');

});
});

如何读取之前的路径?谢谢!

最佳答案

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

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 name 及其$stateParams

我们可以将我们的服务注入(inject)所有范围:

.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

关于AngularJS:从页面获取以前的网址(路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30303567/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com