本文介绍了AngularJs - 取消路由更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 AngularJs 中取消路由更改事件?

How do I cancel route change event in 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 拉下一个模板 &data 如果验证失败,理想情况下应该没有 window.history.back().我什至尝试过 event.preventDefault() 但没有用.

with this even if the validation fails Angular pulls the next template and associated data and then immediately switches back to previous view/route. I don't want angular to pull next template & data if validation fails, ideally there should be no window.history.back(). I even tried event.preventDefault() but no use.

推荐答案

代替 $routeChangeStart 使用 $locationChangeStart

这里是 angularjs 家伙关于它的讨论:https://github.com/angular/angular.js/issues/2109

Here's the discussion about it from the angularjs guys: https://github.com/angular/angular.js/issues/2109

编辑 3/6/2018 您可以在文档中找到它:https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart

Edit 3/6/2018 You can find it in the docs: https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart

示例:

$scope.$on('$locationChangeStart', function(event, next, current) {
    if ($scope.form.$invalid) {
       event.preventDefault();
    }
});

这篇关于AngularJs - 取消路由更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 09:00