在 AngularJS 中,如何在 URL 哈希上添加 $watch? [英] In AngularJS, how do I add a $watch on the URL hash?

查看:28
本文介绍了在 AngularJS 中,如何在 URL 哈希上添加 $watch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

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

但我建议使用事件,例如$routeChangeSuccess默认路由器的代码>:

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

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

$stateChangeSuccess 用于 ui-router

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

这篇关于在 AngularJS 中,如何在 URL 哈希上添加 $watch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆