javascript 在 AngularJS 中,如何在 URL 哈希上添加 $watch?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22002764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:11:31  来源:igfitidea点击:

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

javascriptangularjs

提问by John

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?

使用 Angular,我如何添加一个在哈希更新时触发的监视,无论是通过我的应用程序,还是当浏览器从 URL 栏或后退/前进按钮更新 URL 时?

回答by Klaster_1

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

$scope.$watch接受函数作为第一个参数,所以你可以这样做:

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

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

但我会建议使用的事件,如$routeChangeSuccess缺省路由器

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

or $stateChangeSuccessfor ui-router

$stateChangeSuccess用于ui-router

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

回答by Seung-Hyun Cheong

$locationChangeSuccesscould be better.

$locationChangeSuccess可能会更好。

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

回答by Jin

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,

如果您可以不使用 angular $watch,这也适用。基本上,您观看“hashchange”窗口事件。angularJS 所做的任何事情都是围绕这一点进行的包装。例如,

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

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

});

回答by cat

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.

location.hash 可以通过 angular 内部更新,也可以由用户或浏览器外部更新(单击书签中的链接)。如果它在内部更新 angular 运行 $scope.$apply()。如果外部事件更新 location.hash $watch 只会在下一个 $scope.$apply() 之后触发,例如用户按下您的应用程序中的按钮。

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.

如果您希望使用 $watch,请向“hashchange”添加一个额外的事件侦听器以调用 $apply,或者将所有功能添加到本机 DOM 侦听器,并且不要忘记调用 $apply(),因为这是一个外部调用。

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

OR ...

或者 ...

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