该指令使用SweetAlert来替代confirm() js函数。 https://jsfiddle.net/alfredopacino/njccccsh/
app.directive('confirmLeave',function(){
return {
restrict:"A",
controller:function($scope,$attrs,SweetAlert,$state,$location){
$scope.$on('$destroy', function() {
window.onbeforeunload = undefined;
});
$scope.$parent.$on('$stateChangeStart', function(event, next, current) {
console.log($scope.formname.$dirty)
if($scope.formname.$dirty){
event.preventDefault()
SweetAlert.swal({
title: "Are you sure you want to leave this page?",
text: "Some changes have not been saved.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",confirmButtonText: "Ok",
cancelButtonText: "Cancel",
closeOnConfirm: true,
closeOnCancel: true },
function(isConfirm){
if (isConfirm) {
console.log(next.name)
$state.go(next.name)
//$location.path(next.name)
}
});
}
});
}
}});
它检查表单脏状态,并且在确认的情况下应该遵循下一个路由,但 $state.go() 不会重定向。
最佳答案
似乎 SweetAlert 甚至在您的 $state.go
函数上“触发”,并且不让状态更改,但第二次不显示警报。
我做了一个 fiddle :https://jsfiddle.net/dor2detj/1/
在 fiddle 中,我为 $state.go
函数添加了一点超时(您可以删除超时,它仅用于以下示例),如果您删除此中的 isconfirmed 部分代码:
if($scope.formname.$dirty && isconfirmed === false){
...
}
您可以看到它再次触发了 SweetAlert。
解决方案是设置一个我在此处命名为 isconfirmed
的变量,以防止 SweetAlert 再次触发。
接下来,您可以在 textarea/input/form 中使用 ng-change
再次将变量 isconfirmed
设置为 false,以便在以下情况下再次弹出警报:用户更改输入。
希望您可以根据此示例让您的代码正常运行。
关于javascript - 休假前确认指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37073107/