AngularJS study note: $watch() current URL
I want to use $watch() function to get the current URL, when it changes, do something.
But at first when the URL changes, nothing happened. I used to write it this way, which is WRONG:
$scope.$watch('$location.path()', function(value){
console.log(value);
}
This is wrong because,
$scope.$watch(watchExpression, callbackFunction);
"The first parameter of the $watch method (the “watchExpression”) can be either an Angular string expression (that is evaluated against the $scope), or a function, which is called with $scope as the first parameter. “ I found this explanation from<a href="http://stackoverflow.com/questions/14932119/why-angular-js-parameter-of-a-watch-function-should-be-a-scope-variable"> stackoverflow</a>
It also gives an <a href="http://jsfiddle.net/vojtajina/w39eL/">great example to illustrate</a>
After reading it, I change my code to this:
$scope.$watch(function(){
return $location.path();
}, function(value){
console.log(value);
}
It works! Every time I click a link that changes the URL, console print the URL out.
Written by Guangyi-flyaway
Related protips
4 Responses

Angular also has
$on
Which can be used to watch $route or $location.
$rootScope.$on("$locationChangeStart", function() {
// This will run on every location change, before the
// whole route is processed. Good for things like Identity
// management.
});
Thanks for the tip!

I checked the example, but both ways work for me, whats suppose to happen?

Thank you, ktstowell!
I just started learning AngularJS, so it's really good to know!

Hi neeph,
I test it in Chrome, and if I use the first way, "value" in function(value) is undefined. But in the second way, it can return the current URL correctly.
Have a fresh tip? Share with Coderwall community!
