离开编辑HTML表单之前提示确认 [英] Prompt confirm before Leaving edited html form

查看:595
本文介绍了离开编辑HTML表单之前提示确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户试图离开未保存的编辑形式,一个消息框弹出

If user tries to leave unsaved edited form, a message box pop-up

这个页面,要求您确认您要离开 - 您所输入的数据可能不会被保存。
离开此页面并留在页面

"This page is asking you to confirm that you want to leave - data you have entered may not be saved. Leave Page and Stay on Page"

我们能否通过浏览器的一些特殊功能调用此确认框?我想实现它在AngularJS应用

Can we invoke this confirmation box through some special function of browser? I want to implement it in AngularJS application

推荐答案

术士的答案是有一定道理的,但在这样做,你会伤了可测试性。

Warlock's answer is partly right, but in doing so, you'd break testability.

在折角,你想使用 $窗口,你会想要观看 $脏表单上。你需要有一个名为表格,通知 NAME =myForm会的。然后,你可以 $观看 $脏 $范围在表单上

In Angular, you'd want to use $window, and you'll want to watch $dirty on your form. You'll need to have a named form, notice name="myForm" below. Then you can $watch $dirty on the form in your $scope:

app.controller('MainCtrl', function($scope, $window) {
  $scope.name = 'World';
  var win = $window;
  $scope.$watch('myForm.$dirty', function(value) {
    if(value) {
      win.onbeforeunload = function(){
        return 'Your message here';
      };
    }
  });
});

HTML

<form name="myForm">
  Name: <input type="text" ng-model="name"/>
</form>

下面是一个普拉克证明: http://plnkr.co/edit/3NHpU1

Here's a plunk to demonstrate: http://plnkr.co/edit/3NHpU1

这篇关于离开编辑HTML表单之前提示确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆