angular-ui-router 1.0.x: event.preventDefault & event.defaultPrevented alternative

荒凉一梦 提交于 2019-12-08 21:00:47

问题


I just replaced the $stateChangeStart with $transitions.onStart

$rootScope.$on('$stateChangeStart', function(e, ...){
     e.preventDefault();
     // other code goes here...
});

to

$transitions.onStart({}, function(tras){
     // need a code equivalent to e.preventDefault
     // need a code to identify event.defaultPrevented 
     // other code goes here...

     // get parent states
     _o.util.getAncestorStates(toState.name, true).reverse()
        .forEach(function (state) {
           // certain condition to call event.preventDefault()

           if(event.defaultPrevented) {....}
     });
});

and I guess, we can prevent the transition by adding return $q.reject() instead of e.preventDefault() but I could not understand how the code below return $q.reject() would execute.

Also, how can I replace event.defaultPrevented?

I think should be done something on the transition.promise but not clear.

I am sorry, I can't understand the official doc - https://ui-router.github.io/ng1/docs/latest/ easily. Can anybody help me finding out a better explanation or the replacement for the above code?


回答1:


You can choose one of these two options depend on your logic:

  • Since angular-ui-router 1.0.3 you can use $transition.abort(). Cleaner choice if you have to abort state change after an async call.

    $transitions.onStart({}, function($transition) {
        $transition.abort();
        //more code...
    });
    
  • Also, as @tanmay says in comments, you can use a simple return false to cancel it. This will work in non stable versions too (1.0.0.beta and 1.0.0.rc). (Check it in ui-rooter docs)

    $transitions.onStart({}, function($transition) {
        //code ...
        return false;
    });
    


来源:https://stackoverflow.com/questions/43888603/angular-ui-router-1-0-x-event-preventdefault-event-defaultprevented-alternati

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