1

I have AngularJS application with next route:

/user/:userId

User opens

http://localhost/#/user/1

in browser. Then he changes userId value from 1 to 2 in URL bar and press enter.

My question is: how to hook this moment and do not reload controller? For example, I just want to show message (or do alert() or console.log()) with new userId value on the same page.

1

1 Answer 1

1

You can listen to the '$stateChangeStart' event and call event.preventDefault() to prevent the user from actually going to a new view.

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

Note, if you are adding this listener inside your controller, you should keep a reference to the deregistration function in order to remove the listener when your scope is destroyed.

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

  $scope.$on('$destroy',function(){
    removeListenerFn();
  });

Here is a sample Plunker which you can use to test it out: http://plnkr.co/edit/lYfkPuePGv1GlN1sFjW4?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.