Prevent a stateChange with angular ui router without using $rootScope

Elisabeth picture Elisabeth · Jan 5, 2015 · Viewed 40.8k times · Source

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?

Answer

tsuz picture tsuz · Jan 5, 2015

(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.