angularjs, 이전 루트 경로 가져오기
<h1>{{header}}</h1>
<!-- This Back button has multiple option -->
<!-- In home page it will show menu -->
<!-- In other views it will show back link -->
<a ng-href="{{back.url}}">{{back.text}}</a>
<div ng-view></div>
모듈 구성
$routeProvider.
when('/', {
controller:HomeCtrl,
templateUrl:'home.html'
}).
when('/menu', {
controller:MenuCtrl,
templateUrl:'menu.html'
}).
when('/items', {
controller:ItemsCtrl,
templateUrl:'items.html'
}).
otherwise({
redirectto:'/'
});
컨트롤러
function HomeCtrl($scope, $rootScope){
$rootScope.header = "Home";
$rootScope.back = {url:'#/menu', text:'Menu'};
}
function MenuCtrl($scope, $rootScope){
$rootScope.header = "Menu";
$rootScope.back = {url:'#/', text:'Back'};
}
function ItemsCtrl($scope, $rootScope){
$rootScope.header = "Items";
$rootScope.back = {url:'#/', text:'Back'};
}
컨트롤러에서 볼 수 있듯이 뒤로 버튼의 URL과 텍스트를 하드 코딩했습니다(실제로 이미지를 사용하는 텍스트는 필요 없습니다).이렇게 하면 어떤 경우에는 뒤로 버튼이 잘못 이동한다는 것을 알 수 있습니다.사용할 수 없습니다history.back()
내 뒤로 버튼을 홈 뷰의 메뉴 링크로 변경할 수 있습니다.
그래서 질문입니다.컨트롤러에서 이전 루트 패스를 취득하는 방법 또는 이를 실현하는 더 좋은 방법이 있을까요?
저는 저의 문제에 대한 플런커 데모를 만들었습니다.확인 부탁드립니다.
이 대안은 백 기능도 제공합니다.
템플릿:
<a ng-click='back()'>Back</a>
모듈:
myModule.run(function ($rootScope, $location) {
var history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
$location.path(prevUrl);
};
});
$locationChangeStart 이벤트 또는 $locationChangeSuccess 이벤트, 세 번째 파라미터를 사용합니다.
$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
console.log('success', evt, absNewUrl, absOldUrl);
});
html:
<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>
메인 컨트롤러:
$scope.go_back = function() {
$window.history.back();
};
사용자가 Go Back 링크를 클릭하면 컨트롤러 기능이 호출되어 이전 경로로 돌아갑니다.
@andresh for location Change Success가 아닌 Change Success가 동작했습니다.
//Go back to the previous stage with this back() call
var history = [];
$rootScope.$on('$locationChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
$location.path(prevUrl);
history = []; //Delete history array after going back
};
이것이 현재 에 이전 경로에 대한 참조를 저장하는 방법입니다.$rootScope
:
run(['$rootScope', function($rootScope) {
$rootScope.$on('$locationChangeStart', function() {
$rootScope.previousPage = location.pathname;
});
}]);
Angular 1.x에서는 이벤트청취자를 $rootScope와 결합해야 하지만 $rootScope에 이전 위치 값을 저장하지 않음으로써 향후 코드를 약간 입증해야 합니다.가치를 저장하기에 더 좋은 장소는 서비스입니다.
var app = angular.module('myApp', [])
.service('locationHistoryService', function(){
return {
previousLocation: null,
store: function(location){
this.previousLocation = location;
},
get: function(){
return this.previousLocation;
}
})
.run(['$rootScope', 'locationHistoryService', function($location, locationHistoryService){
$rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){
locationHistoryService.store(oldLocation);
});
}]);
문서화하기 위해:
callback 인수previousRoute
라고 하는 속성을 가지고 있다.$route
이것은, 의 경우와 매우 유사합니다.$route
서비스.불행하게도currentRoute
현재 루트에 대한 정보가 많지 않습니다.
이를 극복하기 위해 저는 이런 시도를 해왔습니다.
$routeProvider.
when('/', {
controller:...,
templateUrl:'...',
routeName:"Home"
}).
when('/menu', {
controller:...,
templateUrl:'...',
routeName:"Site Menu"
})
위의 경로에서는 다음과 같은 커스텀속성을 설정합니다.routeName
가 추가되었습니다.
app.run(function($rootScope, $route){
//Bind the `$routeChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.
$rootScope.$on('$routeChangeSuccess', function(currentRoute, previousRoute) {
//This will give the custom property that we have defined while configuring the routes.
console.log($route.current.routeName)
})
})
위의 코드 수정:
$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
console.log('prev path: ' + absOldUrl.$$route.originalPath);
});
언급URL : https://stackoverflow.com/questions/15175429/angularjs-getting-previous-route-path
'prosource' 카테고리의 다른 글
Spring MockMVC 사용 시 JSON 응답에서 값을 추출하는 방법 (0) | 2023.03.09 |
---|---|
스프링 데이터 저장 시 'documentationPluginsBootstrapper'를 시작하지 못했습니다. (0) | 2023.03.09 |
사용자/게스트가 WooCommerce에서 특정 제품을 구입했는지 확인합니다. (0) | 2023.03.09 |
스프링 @프로퍼티 자동배선 vs 컨스트럭터 (0) | 2023.03.09 |
클래스 컴포넌트에서 react-redux useSelector를 사용하려면 어떻게 해야 합니까? (0) | 2023.03.09 |