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?
Watching a $locationProvider in Angular.js
Asked Answered
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.
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
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
});
© 2022 - 2024 — McMap. All rights reserved.