在Angular.js中观察$ locationProvider

时间:2023-01-16 15:15:39

I need to watch changes on the URL bar and do certain actions based on that. I wondered what's the best way to add a watch to view changes to it?

我需要在URL栏上观察更改并根据它执行某些操作。我想知道添加手表以查看更改的最佳方法是什么?

2 个解决方案

#1


12  

Events exist, they're just undocumented for some reason.

事件存在,由于某种原因它们只是没有记录。

Try the following events: $locationChangeStart and $locationChangeSuccess

请尝试以下事件:$ locationChangeStart和$ locationChangeSuccess

scope.$on('$locationChangeStart', function (event, newLoc, oldLoc){
   console.log('changing to: ' + newLoc);
});

scope.$on('$locationChangeSuccess', function (event, newLoc, oldLoc){
   console.log('changed to: ' + newLoc);
});

Or you can $watch any value you want by passing a function into the $watch's first argument as Anders suggested:

或者你可以通过将函数传递给$ watch的第一个参数来监视你想要的任何值,如Anders建议的那样:

scope.$watch(function() { return $location.path(); }, function(newLoc, oldLoc){
   console.log(newLoc, oldLoc);
});

However this will create a little more overhead on your $digest.

但是,这会在$ digest上产生更多的开销。

#2


1  

Assuming that you have requested the $location object in your controller, you can do it like this:

假设您已在控制器中请求$ location对象,您可以这样做:

$scope.$watch(function() { return $location.path() }, function() {
    // Do stuff when the location changes
});

#1


12  

Events exist, they're just undocumented for some reason.

事件存在,由于某种原因它们只是没有记录。

Try the following events: $locationChangeStart and $locationChangeSuccess

请尝试以下事件:$ locationChangeStart和$ locationChangeSuccess

scope.$on('$locationChangeStart', function (event, newLoc, oldLoc){
   console.log('changing to: ' + newLoc);
});

scope.$on('$locationChangeSuccess', function (event, newLoc, oldLoc){
   console.log('changed to: ' + newLoc);
});

Or you can $watch any value you want by passing a function into the $watch's first argument as Anders suggested:

或者你可以通过将函数传递给$ watch的第一个参数来监视你想要的任何值,如Anders建议的那样:

scope.$watch(function() { return $location.path(); }, function(newLoc, oldLoc){
   console.log(newLoc, oldLoc);
});

However this will create a little more overhead on your $digest.

但是,这会在$ digest上产生更多的开销。

#2


1  

Assuming that you have requested the $location object in your controller, you can do it like this:

假设您已在控制器中请求$ location对象,您可以这样做:

$scope.$watch(function() { return $location.path() }, function() {
    // Do stuff when the location changes
});