这是我的问题,我有两个视图(View1和View2)和每个视图的控制器(Ctrl1和Ctrl2)。在View1中,我试图警告用户,他不经意地离开页面而不保存更改。
我正在使用window.onbeforeunload,它的工作原理很好,但我的问题是,即使我只有在一个控制器上只能运行,事件似乎也被触发在第二个控制器!但我甚至没有那个事件在那里。当用户离开页面并且存在未保存的更改时,如果用户关闭警报并离开页面,他将被接收到第二个视图,如果用户尝试离开此视图,则会被onbeforeunload警告,我们也会收到关于未保存更改的警告!甚至不是这样的情况!为什么会发生这种情况?
我也使用$ locationChangeStart,它工作得很好,但只有当用户更改路由时,而不是刷新浏览器,点击“返回”或尝试关闭它,这就是为什么我被迫使用onbeforeunload如果你是一个更好的方法,请让我知道)。任何帮助或更好的方法将不胜感激!
//In this controller I check for window.onbeforeunload app.controller("Ctrl1",function ($scope,...)){ window.onbeforeunload = function (event) { //Check if there was any change,if no changes,then simply let the user leave if(!$scope.form.$dirty){ return; } var message = 'If you leave this page you are going to lose all unsaved changes,are you sure you want to leave?'; if (typeof event == 'undefined') { event = window.event; } if (event) { event.returnValue = message; } return message; } //This works only when user changes routes,not when user refreshes the browsers,goes to prevIoUs page or try to close the browser $scope.$on('$locationChangeStart',function( event ) { if (!$scope.form.$dirty) return; var answer = confirm('If you leave this page you are going to lose all unsaved changes,are you sure you want to leave?') if (!answer) { event.preventDefault(); } }); } //This other controller has no window.onbeforeunload,yet the event is triggered here too! app.controller("Ctrl2",...)){ //Other cool stuff ... }
我尝试使用$ location.path()检查当前路径,以便在视图中警告用户,我希望触发onbeforeunload,但这似乎是一个“hacky”,解决方案是在另一个上执行onbeforeunload控制器。
我在第一个添加了$ location.path()!=’/ view1’,似乎有效,但对我来说似乎不对,除了我不仅有两个意见,我有几个意见,这将得到涉及更多控制器的棘手:
app.controller("Ctrl1",then simply let the user leave if($location.path() != '/view1' || !$scope.form.$dirty){ return; } var message = 'If you leave this page you are going to lose all unsaved changes,are you sure you want to leave?') if (!answer) { event.preventDefault(); } }); }
当定义它的控制器超出范围时,取消注册onbeforeunload事件:
$scope.$on('$destroy',function() { delete window.onbeforeunload; });