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?
The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.
The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.
absURL(); Example 1: in this example, we are using the $location. absURL() method to get the complete URL of the current page.
watchers is nothing but dirty checking, which keeps a track of the old value and new value. They are getting evaluated on each digest cycle. It can be combination of scope variable or any expression. Angular does collect all of this watchers on each digest cycle and mainatain it inside $$watchers array.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With