Prevent a stateChange with angular ui router without using $rootScope

北城以北 提交于 2019-12-31 08:34:15

问题


My user can leave a state but before I want to show a modal dialog "Do you want to save?"

ONLY if the user data is dirty that means changed.

What I do NOT want is to stick a isDirty property in my EditController to the $rootScope go to the stateChangeStart event and check there for isDirty and then show/not the save dialog.

Prevent global variables says every javascript beginner book...

1.) What is then the pro way to prevent a state change without hacking the $rootscope?.

2.) Are there any helper libraries for ui-router which enhance the ui-router offering function hooks inside the controller to encapsulate the ui logic?


回答1:


(1) According to the docs under State Change Events

 $rootScope.$on('$stateChangeStart', 
      function(event, toState, toParams, fromState, fromParams){ 
          event.preventDefault(); 
          // transitionTo() promise will be rejected with 
          // a 'transition prevented' error
 })

You could change $rootScope to $scope wherever appropriate and works.

Under Attach Custom Data to State Objects, you can pass on custom data.

(2) I'm not sure what you're asking but factories/services/providers would really help.




回答2:


Using $transitions.onStart (angular-ui-router 1.0.0-rc) you can return a boolean. If false the transition will be cancelled.

$transitions.onStart({}, function (trans) { 
    var answer = confirm("Want to leave this page?")
    if (!answer) {
        return false;
    }
});

Here is the documentation: https://ui-router.github.io/ng1/docs/latest/modules/transition.html#hookresult




回答3:


Though at the time of writing it is not a part of the stable release, the 1.0 release of the UI-router will use the return value of onEnter/onExit to prevent navigation.

See GitHub issue 2219



来源:https://stackoverflow.com/questions/27787380/prevent-a-statechange-with-angular-ui-router-without-using-rootscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!