Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $locationChangeStart fired upon page load?

Tags:

angularjs

Recently I've stumbled upon a very strange code in production that is seemingly using the fact that under some conditions Angular may fire the $locationChangeStart event upon the initial page load. Moreover the next parameter value will be equal to the current value. That seems very odd to me.

I didn't find any relevant documentation for that but here is the fiddle that shows such a situation http://jsfiddle.net/tJSPt/327/

Probably the only difference is that in production we are using the manual Angular bootstrap.

Can anyone explain or point to the trustful sources of information on why is that event triggered upon the page load? Is that something we have to expect or that is just the particularity of the current Angular implementation or our way of using it?

like image 326
xenn_33 Avatar asked Feb 17 '15 21:02

xenn_33


Video Answer


1 Answers

I have experienced this recently but the reason it happened was because I'm using ui-router and the controllerAs syntax. Perhaps you are too?

I stumbled upon this link that helped me out: History should not be changed until after route resolvers have completed

I listened to the $locationChangeStart broadcast but it hit the breakpoint when I entered the state instead of when exciting.

I fixed mine by doing the following:

  1. I listened to $stateChangeStart instead.
  2. I had to move the code above var vm = this;

Here's my code look like after:

// ...     
$scope.$on('$stateChangeStart', function (event) {
        if (vm.myForm!= null && vm.myForm.$dirty) {
            if (!confirm("Are you sure you want to leave this page?")) {
                event.preventDefault();
            }
        }
    });

var vm = this;
// vm.xxx = xxxx; .etc ...
like image 67
Xaero Avatar answered Oct 25 '22 13:10

Xaero