Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In AngularJS, how do I add a $watch on the URL hash?

Using Angular, how can I add a watch that is fired when the hash is updated, either by my application, or when the browser updates the URL from either the URL bar or the back/forward buttons?

like image 575
John Avatar asked Feb 25 '14 01:02

John


People also ask

How to update the URL in AngularJS?

If the user is maximizing it the first time, share the url to this maximized view with the maximizedWidgetId on the UI. As long as you use $location(which is just a wrapper over native location object) to update the path it will refresh the view. Not only $location will refresh the view.

How does $Watch work AngularJS?

$watch(function() {}, function() {} ); The first function is the value function and the second function is the listener function. The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time.

Which method of $location service is used to get the URL without base prefix?

hash() Method: It is a read and writes method of $location service. It returns the current hash value of the current URL when called without parameters and when called with parameters it returns the$location object.


2 Answers

$scope.$watch accepts function as the first argument, so you can do this:

$scope.$watch(function () {
    return location.hash
}, function (value) {
    // do stuff
});

But I would recommend using events, such as $routeChangeSuccess for default router:

$scope.$on("$routeChangeSuccess", function () {})

or $stateChangeSuccess for ui-router

$scope.$on("$stateChangeSuccess", function () {})
like image 184
Klaster_1 Avatar answered Sep 29 '22 07:09

Klaster_1


$locationChangeSuccess could be better.

$scope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl){
    // TODO What you want on the event.
});
like image 30
Seung-Hyun Cheong Avatar answered Sep 29 '22 05:09

Seung-Hyun Cheong