Javascript 当用户离开页面时在 angularjs 中显示警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14809686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Showing alert in angularjs when user leaves a page
提问by iJade
I'm an angularjs new bee. I'm trying to write a validation which alerts the user when he tries to close the browser window.
我是 angularjs 的新蜜蜂。我正在尝试编写一个验证,当他尝试关闭浏览器窗口时提醒用户。
I have 2 links on my page v1 and v2.When clicked on the links it takes to the specific pages. Here is the code to redirect to v1 and v2
我的页面 v1 和 v2 上有 2 个链接。单击链接时,它会转到特定页面。这是重定向到 v1 和 v2 的代码
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/v1', {templateUrl: 'pages/v_1.html', controller: MyCtrl1});
$routeProvider.when('/v2', {templateUrl: 'pages/v_2.html', controller: MyCtrl2});
$routeProvider.otherwise({redirectTo: '/v1'});
}]);
I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2. Any pointers on how to achieve this would be appreciated.
当用户单击 v1 时,我想弹出一条消息,“如果他希望继续,他将要离开 v1”,并且在单击 v2 时也是如此。任何有关如何实现这一目标的指示将不胜感激。
I got an answer herebut it pops up the message after every time interval.
Updated Code;
更新代码;
Controllers
控制器
function MyCtrl1() {
$scope.$on('$locationChangeStart', function (event, next, current) {
if ('your condition') {
event.preventDefault();
MessageService.showConfirmation(
'Are you sure?',
MessageService.MessageOptions.YES_NO, {
'YES': function () {
blockNavigation = false;
$location.url($location.url(next).hash());
$rootScope.$apply();
},
'NO': function () {
MessageService.clear();
$log.log('NO Selected')
}
});
}
});
}
MyCtrl1.$inject = [];
function MyCtrl2() {}
MyCtrl2.$inject = [];
回答by Scheintod
The code for the confirmation dialogue can be written shorter this way:
确认对话的代码可以这样写得更短:
$scope.$on('$locationChangeStart', function( event ) {
var answer = confirm("Are you sure you want to leave this page?")
if (!answer) {
event.preventDefault();
}
});
回答by Yair Nevet
Lets seperate your question, you are asking about two different things:
让我们分开你的问题,你问的是两个不同的事情:
1.
1.
I'm trying to write a validation which alerts the user when he tries to close the browser window.
我正在尝试编写一个验证,当他尝试关闭浏览器窗口时提醒用户。
2.
2.
I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.
当用户单击 v1 时,我想弹出一条消息,“如果他希望继续,他将要离开 v1”,并且在单击 v2 时也是如此。
For the first question, do it this way:
对于第一个问题,这样做:
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
And for the second question, do it this way:
对于第二个问题,请这样做:
You should handle the $locationChangeStartevent in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:
您应该处理$locationChangeStart事件以连接到视图转换事件,因此使用此代码来处理控制器中的转换验证:
function MyCtrl1($scope) {
$scope.$on('$locationChangeStart', function(event) {
var answer = confirm("Are you sure you want to leave this page?")
if (!answer) {
event.preventDefault();
}
});
}
回答by Christopher Davies
Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.
这是我使用的指令。当表单被卸载时,它会自动清理自己。如果您想阻止提示触发(例如,因为您成功保存了表单),请调用 $scope.FORMNAME.$setPristine(),其中 FORMNAME 是您想要阻止提示的表单的名称。
.directive('dirtyTracking', [function () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = $scope[$element.attr('name')];
return formObj && formObj.$pristine === false;
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes. Are you sure you want to leave this page?';
}
}
window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
回答by facultymatt
As you've discovered above, you can use a combination of window.onbeforeunloadand $locationChangeStartto message the user. In addition, you can utilize ngForm.$dirtyto only message the user when they have made changes.
正如你在前面已经发现,可以使用的组合window.onbeforeunload和$locationChangeStart用户信息。此外,您可以使用ngForm.$dirty仅在用户进行更改时向用户发送消息。
I've written an angularjs directive that you can apply to any form that will automatically watch for changes and message the user if they reload the page or navigate away. @see https://github.com/facultymatt/angular-unsavedChanges
我已经编写了一个 angularjs 指令,您可以将其应用于任何表单,如果用户重新加载页面或导航离开,它将自动监视更改并向用户发送消息。@see https://github.com/facultymatt/angular-unsavedChanges
Hopefully you find this directive useful!
希望你发现这个指令有用!
回答by Brent Matzelle
The other examples here work fine for the old versions of ui-router (>=0.3.x) but all state events, such as $stateChangeStart, are deprecated as of 1.0. The new ui-router 1.0 code uses the $transitions service. So you need to inject $transitionsinto your component then use the $transitions.onBeforemethod as the code below demonstrates.
这里的其他例子做工精细的老版本用户界面路由器(> = 0.3.X),但所有状态的事件,比如$stateChangeStart,被弃用的1.0。新的 ui-router 1.0 代码使用$transitions 服务。因此,您需要注入$transitions到您的组件中,然后使用$transitions.onBefore方法,如下面的代码所示。
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
This is just a super simple example. The $transitionsservice can accept more complicated responses such as promises. See the HookResult typefor more information.
这只是一个超级简单的例子。该$transitions服务可以接受更复杂的响应,例如承诺。有关更多信息,请参阅HookResult 类型。
回答by Srija Nakka
$scope.rtGo = function(){
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
}
$scope.init = function () {
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
};
Reload page: using init
重新加载页面:使用 init

