Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watching a $locationProvider in Angular.js

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?

like image 245
Lior Avatar asked Feb 19 '13 14:02

Lior


People also ask

What is $location in AngularJS?

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.

What does $Watch do 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.

Which method of $location service is used to get the full URL of the current web page?

absURL(); Example 1: in this example, we are using the $location. absURL() method to get the complete URL of the current page.

What is watcher in angular?

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.


2 Answers

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.

like image 136
Ben Lesh Avatar answered Oct 05 '22 23:10

Ben Lesh


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
});
like image 45
Anders Ekdahl Avatar answered Oct 06 '22 01:10

Anders Ekdahl