4

我需要一个类似于$routeChangeSuccess$location.search() 变量的事件。我正在调用 $location.search('newview'),并且需要一种方法来知道它何时发生变化。

谢谢!

4

2 回答 2

15

你应该使用$scope.$watch

$scope.$watch(function(){ return $location.search() }, function(){
  // reaction
});

$watch在 Angular文档中查看更多信息。

如果您只是想在查询字符串中添加“newview”,则上述代码将起作用。

即从http://server/pagehttp://server/page?newvalue

但是,如果您正在寻找“newview”中的更改,则上述代码将不起作用。

即从http://server/page?newvalue=ahttp://server/page?newvalue=b

您将需要使用“objectEquality”参数来调用 $watch。这会导致 $watch 使用值相等,而不是对象引用相等。

$scope.$watch(function(){ return $location.search() }, function(){
  // reaction
}, true);

注意添加了第三个参数(true)。

于 2013-02-14T05:51:22.703 回答
2

您可以在控制器中侦听 $routeUpdate 事件:

$scope.$on('$routeUpdate', function(){
   $scope.sort = $location.search().sort;
   $scope.order = $location.search().order;
   $scope.offset = $location.search().offset;
});
于 2016-11-22T06:13:21.333 回答