如何在AngularJs中取消路由变更事件?
我当前的代码是
$rootScope.$on("$routeChangeStart", function (event, next, current) {
// do some validation checks
if(validation checks fails){
console.log("validation failed");
window.history.back(); // Cancel Route Change and stay on current page
}
});
这样,即使验证失败,Angular也会提取下一个模板和相关数据,然后立即切换回以前的视图/路由。如果验证失败,我不希望angular拉取下一个模板和数据,理想情况下不应该有window.history.back()。我甚至尝试过event.preventDefault(),但没有用。
发布于 2014-02-04 17:17:41
更完整的代码示例,使用$locationChangeStart
// assuming you have a module called app, with a
angular.module('app')
.controller(
'MyRootController',
function($scope, $location, $rootScope, $log) {
// your controller initialization here ...
$rootScope.$on("$locationChangeStart", function(event, next, current) {
$log.info("location changing to:" + next);
});
}
);
我对在我的根控制器(顶层控制器)中挂接这一点并不完全满意。如果有更好的模式,我很想知道。我刚接触angular :-)
发布于 2015-10-16 15:37:00
对于任何偶然发现这一点的人来说,这是一个古老的问题(至少在angular 1.4中),你可以这样做:
.run(function($rootScope, authenticationService) {
$rootScope.$on('$routeChangeStart', function (event, next) {
if (next.require == undefined) return
var require = next.require
var authorized = authenticationService.satisfy(require);
if (!authorized) {
$rootScope.error = "Not authorized!"
event.preventDefault()
}
})
})
发布于 2014-11-16 07:20:49
这是我的解决方案,它对我有效,但我不知道我是否在正确的道路上,因为我对web技术是新的。
var app = angular.module("app", ['ngRoute', 'ngCookies']);
app.run(function($rootScope, $location, $cookieStore){
$rootScope.$on('$routeChangeStart', function(event, route){
if (route.mustBeLoggedOn && angular.isUndefined($cookieStore.get("user"))) {
// reload the login route
jError(
'You must be logged on to visit this page',
{
autoHide : true,
TimeShown : 3000,
HorizontalPosition : 'right',
VerticalPosition : 'top',
onCompleted : function(){
window.location = '#/signIn';
window.setTimeout(function(){
}, 3000)
}
});
}
});
});
app.config(function($routeProvider){
$routeProvider
.when("/signIn",{
controller: "SignInController",
templateUrl: "partials/signIn.html",
mustBeLoggedOn: false
});
https://stackoverflow.com/questions/16344223
复制相似问题