View $ locationProvider in Angular.js

I need to monitor changes in the URL string and take certain actions based on this. I wondered what is the best way to add a watch to view changes?

+5
source share
2 answers

Events exist, for some reason they are undocumented.

Try the following events: $locationChangeStartand$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 the function to the first argument of $ watch, as Anders suggested:

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

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

+12
source

Assuming you 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
});
+1
source

All Articles