Watching a $locationProvider in Angular.js
Asked Answered
V

2

5

I need to watch changes on the URL bar and do certain actions based on that. I wondered what's the best way to add a watch to view changes to it?

Veal answered 19/2, 2013 at 14:33 Comment(0)
B
12

Events exist, they're just undocumented for some reason.

Try the following events: $locationChangeStart and $locationChangeSuccess

scope.$on('$locationChangeStart', function (event, newLoc, oldLoc){
   console.log('changing to: ' + newLoc);
});

scope.$on('$locationChangeSuccess', function (event, newLoc, oldLoc){
   console.log('changed to: ' + newLoc);
});

Or you can $watch any value you want by passing a function into the $watch's first argument as Anders suggested:

scope.$watch(function() { return $location.path(); }, function(newLoc, oldLoc){
   console.log(newLoc, oldLoc);
});

However this will create a little more overhead on your $digest.

Banff answered 19/2, 2013 at 15:45 Comment(4)
Thanks @blesh. trying to identify when the two events are emitted and whats the difference between them. any ideas?Veal
It's all set up in the initialization code for $location. Have a look at the source on GitHub. Just CTRL+F for $locationChangeStart. It's basically the same as the $watch() method suggested, but it's already set up for you, so there's less overhead.Banff
In a nutshell, $locationChangeStart happens first and gives you an option to prevent the change with preventDefault() on the event object passed to it. $locationChangeSuccess fires after the location is successfully changed. (rather, when you've committed to changing the location).Banff
so we should consider $locationChangeStart and $locationChangeSuccess to have a before and after relationship to a route?Hughmanick
R
1

Assuming that you have requested the $location object in your controller, you can do it like this:

$scope.$watch(function() { return $location.path() }, function() {
    // Do stuff when the location changes
});
Rehabilitation answered 19/2, 2013 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.