admin管理员组

文章数量:1418336

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?

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?

Share Improve this question asked Feb 25, 2014 at 1:23 JohnJohn 3,9467 gold badges32 silver badges45 bronze badges 1
  • 1 Not sure about the hash itself, but the way I always check for that is $rootScope.$on('$routeChangeStart', function (event, next, current) {}); – francisco.preller Commented Feb 25, 2014 at 1:27
Add a comment  | 

4 Answers 4

Reset to default 25

$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 () {})

$locationChangeSuccess could be better.

$scope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl){
    // TODO What you want on the event.
});

This works too if you're okay with not using the angular $watch. Basically, you watch 'hashchange' windows event. whatever angularJS does is a wrapper around this. For example,

$($window).bind('hashchange', function () {

    // Do what you need to do here like... getting imageId from #
    var currentImageId = $location.search().imageId;

});

location.hash can be updated internally by angular or externally by the user or the browser (click link in bookmarks). If it is updated internally angular runs a $scope.$apply(). If an external event updates location.hash $watch does only fire UNTIL AFTER the next $scope.$apply(), e.g. a user pushes a button within your app.

If you wish to use a $watch, add an additional event listener to "hashchange" to call $apply, or add all functionality to the native DOM listener AND do not forget to call $apply(), as this is an external call.

window.addEventListener("hashchange", function(){ $scope.$apply(); }, false);

OR ...

window.addEventListener("hashchange", function(){ me._locationHashChanged(); $scope.$apply(); }, false);

本文标签: javascriptIn AngularJShow do I add a watch on the URL hashStack Overflow