有这样的场景:
- 浏览器重新加载,
- 关闭选项卡
- 关闭浏览器
- 路线变更(例如点击链接)
- 浏览器后退按钮被点击。或 history.go(-1)。3 根手指在 Macbook 上轻扫。
如果用户填写了某种表格或正在写作中,我们会想要阻止这种情况。
我编写了这段代码,它工作得很好,但如果我不能在几个文本字段上实现它,它绝对没有用。目前它只检查我们是否在#/write url。它不检查任何输入。
处理这个问题的角度方法是什么?检查目标文本字段的最佳方法是什么。指令是解决方案吗?就像是:
<input type="text" warningOnLeave ng-model="title"/>
或者
<form warningOnLeave name="myForm">...</form>
 $rootScope.$on('$locationChangeStart', function(event, current, previous){
    console.log(current);
    console.log(previous);
    // Prevent route change behaviour
    if(previous == 'http://localhost/#/write' && current != previous){
        var answer = confirm ("You have not saved your text yet. Are you sure you want to leave?");
        if (!answer)
            event.preventDefault();     
    }
});
/** 
   Prevent browser behaviour
*/
window.onbeforeunload = function (e) {
    if(document.URL == 'http://localhost/#/write'){
        e = e || window.event;
        // For IE and Firefox prior to version 4
        if (e) {
            e.returnValue = 'You have not saved your text yet.';
        }
        // For Safari
        return 'You have not saved your text yet.';
    }
    else
        return;
}