使用$location.path跳转页面失效问题排查
解决SweetAlert回调中$location.path跳转失效的问题
这个问题我之前也碰到过!核心原因是SweetAlert的回调函数运行在AngularJS的变更检测(Digest Cycle)之外,所以你修改$location.path后,Angular根本没察觉到这个变化,自然不会触发路由跳转;而console.log是原生JavaScript语句,不受Angular上下文的限制,所以能正常输出。
解决方案1:手动触发Angular的变更检测
把$location.path的调用包裹在$scope.$apply()里,强制Angular执行变更检测,感知到路由的变化:
setTimeout(function () { swal({ title: "HI", text: "Welcome.", type: "warning", confirmButtonText: "OK" }, function () { // 用$apply包裹路由跳转逻辑 $scope.$apply(function() { $location.path("home"); }); console.log("Redirect is working"); }); }, 100);
解决方案2:改用Angular原生的$timeout代替setTimeout
如果你不需要原生setTimeout的特殊行为,建议换成Angular的$timeout服务——它会自动在回调结束后触发变更检测,不过SweetAlert的回调仍然需要手动$apply(因为它还是第三方库的回调):
// 记得要注入$timeout服务到你的控制器里 $timeout(function () { swal({ title: "HI", text: "Welcome.", type: "warning", confirmButtonText: "OK" }, function () { $scope.$apply(function() { $location.path("home"); }); console.log("Redirect is working"); }); }, 100);
补充说明
AngularJS的所有数据更新、路由变化,都依赖于它的Digest Cycle来感知和处理。当你在Angular上下文之外(比如原生JS回调、第三方库回调、原生setTimeout)修改Angular的服务(比如$location、$scope)时,Angular无法自动检测到这些变化,必须通过$scope.$apply()手动触发一次Digest Cycle,让Angular处理这些变更。
内容的提问来源于stack exchange,提问作者Animay
相关产品推荐
相关产品推荐

