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

Joh*_*ohn 19 javascript angularjs

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

Kla*_*r_1 25

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

$scope.$watch(function () {
    return location.hash
}, function (value) {
    // do stuff
});
Run Code Online (Sandbox Code Playgroud)

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

$scope.$on("$routeChangeSuccess", function () {})
Run Code Online (Sandbox Code Playgroud)

或者$stateChangeSuccess用于ui-router

$scope.$on("$stateChangeSuccess", function () {})
Run Code Online (Sandbox Code Playgroud)

  • 只有散列更改时才会触发`$ routeChangeSuccess`. (5认同)

小智 17

$ locationChangeSuccess可能会更好.

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

  • @PhamHuyAnh它正在为我工​​作,我只是在项目中使用Angular 1.2.21.确保你注入`$ location`.如果不这样做,它将不适用于散列更改事件观察 (2认同)

Jin*_*Jin 7

如果您没有使用角度$ watch,这也可以.基本上,你看'hashchange'窗口事件.无论angularJS做什么都是这个的包装.例如,

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

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

});
Run Code Online (Sandbox Code Playgroud)