fsxrrg
Last Updated: October 12, 2017
·
12.17K
· guangyi
Cfccdf00acb76649add0727077e3a1c7

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.

Say Thanks
Respond

4 Responses
Add your response

10799
470b4f31c2e48aa4861a4e34774b83a1

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!

over 1 year ago ·
10802
48903 705091365 7020401 n normal

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

over 1 year ago ·
10848
Cfccdf00acb76649add0727077e3a1c7

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

over 1 year ago ·
10849
Cfccdf00acb76649add0727077e3a1c7

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.

over 1 year ago ·