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 |4 Answers
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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1737424247a3948880.html
$rootScope.$on('$routeChangeStart', function (event, next, current) {});
– francisco.preller Commented Feb 25, 2014 at 1:27