在我的应用程序中,我使用一些查询字符串参数来解析用于预选某些数据的链接。但我想为用户隐藏这些参数。例如,在我使用像 localhost/myapp#/settings?key=dataGrid&value=10
这样的路由的地方,我想清除这些参数并向用户显示像 localhost/myapp# 这样的路由/设置
。
我试过这样的:
angular.module('myApp')
.run(['$rootScope', '$sce', '$location', '$route',
function($rootScope, $sce, $location, $route) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if ($location.url().indexOf('?key=')) {
var newLocationPath = $location.url().substring(
0, $location.url().indexOf('?key='));
$location.path(newLocationPath).search('');
}
});
}]);
但它什么都不做。在 StackOverflow 上,我发现了一些关于使用 $rootScope.$Apply
的信息,但如果尝试使用它,我会收到此错误:[$rootScope:inprog] $digest already in progress
。
最佳答案
尝试:$locationChangeStart 来处理页面更改。您的代码如下:
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
$rootScope.target = $location.search()['key']; // (equivalent) key = GET[key]
// $rootScope.target = $location.search().key; // Other solution
});
要将参数设置为来自 Controller 的 url(不使用链接),代码如下:
myApp.controller('MyCtrl',function($scope, $location) {
// setParam('key', 'dataGrid')
$scope.setParam = function(param, value) {
$location.search(param, value); // domain.com/#/page?key=dataGrid
};
});
实例: http://jsfiddle.net/Chofoteddy/3wFeR/
也就是说,您的代码如下:
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
var param = $location.search()['key'];
$location.path(param).search(''); // Change url and clean params
});
关于javascript - AngularJS:如何在 routeChangeStart 事件中更改位置路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22841015/