在导航到其他视图之前警告用户

Kod*_*der 6 angularjs angular-ui-router

在用户导航离开应用程序中的某些页面之前,我想警告用户并获得确认,例如撰写新的消息视图.我可以捕获哪些事件并取消/继续实现这一目标?

har*_*shr 7

您应该处理$ locationChangeStart事件以挂接到查看转换事件,因此使用此代码来处理控制器中的转换验证:

$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)

你也可以使用这个指令angularjs-unsaved-changes,它比每个控制器写一个更可重用.


Moh*_*and 7

如果您说某个链接或按钮导航到另一个路线或州,您只需显示一个确认导航的模式:

<a href="" ng-click="goToAnotherState()">Go Away...</a>

$scope.goToAnotherState = function(){

//show modal and get confirmating however your like
  if(modalResponse.Ok){
     $state.go('anotherState');
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是在$locationChangeStartui-router 的情况下这样做,但如果你只是在这里看到这个,那么第一种方法更好.$locationChangeStart做法:

$rootScope.$on('$locationChangeStart', function (event, next, prev) {
  event.preventDefault();
  //show modal
  if(modalResponse.ok){
    var destination = next.substr(next.indexOf('#') + 1, next.length).trim();
    $location.path(destination)
  }
}
Run Code Online (Sandbox Code Playgroud)