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 |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);
本文标签: javascriptIn AngularJShow do I add a watch on the URL hashStack Overflow
版权声明:本文标题:javascript - In AngularJS, how do I add a $watch on the URL hash? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737424246a1988967.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
$rootScope.$on('$routeChangeStart', function (event, next, current) {});
– francisco.preller Commented Feb 25, 2014 at 1:27