我需要有可能询问用户他/她是否要离开页面.我读到他的可能性,但是当我进入页面而不是当我离开页面时事件被触发. onExit可以工作,但是这个事件我必须在...... .routes.js中定义,我需要访问控制器的属性和功能.是否有一个由页面退出触发的事件?
$scope.$on('$locationChangeStart', function( event ) {
var answer = confirm("Are you sure you want to leave this page?")
if (!answer) {
event.preventDefault();
}
});
Run Code Online (Sandbox Code Playgroud)
您提到的$ stateChangeStart有利于您的需求:实际上来自ui-router文档:
$ stateChangeStart - 转换开始时触发.
那是用户离开之前的状态.
在这里,您可以找到一个非常相似的问题的答案:
而且还是一个工作片段.
这可以通过多种方式实现,
1-使用$ locationChangeStart技术并在显示消息之前验证这是否是当前位置.以下示例,
$scope.$on('$locationChangeStart', function( event, next, current) {
// match Current URL and If it true show message.
if (current.match("\/yourCurrentRoute")) {
var answer = confirm("Are you sure you want to leave this page?");
if (!answer) {
event.preventDefault();
}else {
//Do whatever else you want to do
}
}
});
Run Code Online (Sandbox Code Playgroud)
2-如果您使用的是Ui-Router,它有onExit回拨选项,例如下面的例子,
$stateProvider.state("contacts", {
template: "<h1>{{title}}</h1>",
resolve: { title: 'My Contacts' },
controller: function($scope, title){
$scope.title = title;
},
onExit: function(title){
if(title){ ... do something ... }
}
})
Run Code Online (Sandbox Code Playgroud)
3 - 也有一种非角度的方式.
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;
}
Run Code Online (Sandbox Code Playgroud)
4 - 如果此页面具有表单,则使用此指令,在卸载表单时自动清除.如果要阻止提示被触发(例如,因为您已成功保存表单),请调用$ 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();
}
});
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
5-还有另一种使用$ destroy的方法,它在控制器被销毁时触发,在控制器内写入.
$scope.$on('$destroy', function () {
// display error message
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3053 次 |
最近记录: |