加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

一个控制器中的AngularJS window.onbeforeunload正在另一个控制

发布时间:2020-12-17 08:11:45 所属栏目:安全 来源:网络整理
导读:这是我的问题,我有两个视图(View1和View2)和每个视图的控制器(Ctrl1和Ctrl2)。在View1中,我试图警告用户,他不经意地离开页面而不保存更改。 我正在使用window.onbeforeunload,它的工作原理很好,但我的问题是,即使我只有在一个控制器上只能运行,事件似
这是我的问题,我有两个视图(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()检查当前路径,以便在视图中警告用户,我希望触发onb??eforeunload,但这似乎是一个“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;
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读