Below is the code so far
Anders's answer works fine, However, for people who uses Angular ui-router, you should use '$stateChangeStart' instead of '$locationChangeStart'.
'$stateChangeStart'
'$locationChangeStart'