AngularJS搜索更改事件

时间:2013-02-14 04:24:14

标签: search angularjs

我需要像$routeChangeSuccess这样的事件,但需要$ location.search()变量。我正在调用$ location.search('newview'),并且需要一种方法来了解它何时发生变化。

谢谢!

2 个答案:

答案 0 :(得分:15)

您应该使用$scope.$watch

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

在Angular docs中详细了解$watch

如果您只是想要添加'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);

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

答案 1 :(得分:2)

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

$scope.$on('$routeUpdate', function(){
   $scope.sort = $location.search().sort;
   $scope.order = $location.search().order;
   $scope.offset = $location.search().offset;
});