AngularJs $watch on $location.search doesn't work when reloadOnSearch is false

六眼飞鱼酱① 提交于 2019-11-28 04:51:11

You can listen for $routeUpdate event in your controller:

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

In case you don't use Angular's route resolution or you just want to know whenever $location changes, there is an event just for that purpose

$rootScope.$on('$locationChangeSuccess', function(event){
        var url = $location.url(),
            params = $location.search();
})
Anders Ekdahl

Stewies answer is correct, you should listen to $routeUpdate events for that since it's more efficient.

But to answer why your watch isn't working; when you watch location.search(), you're watching if the reference that the search method returns is the same or not. And it will return the reference to the same object every time you call it, which is why your watch isn't firing. That is, even if the search parameters change, it's still the same object that is returned. To get around that, you can pass in true as the third argument to $watch. That will tell Angular to compare by value, not reference. But be careful when creating such watches, because they will consume more memory, and take longer to execute. So that's why you should do it like stewie said.

Use

$scope.$watch(function(){ return $location.search() }, function(params){
    console.log(params);
});

instead.

CodeOverRide

Watch the change on routeUpdate like this in controller:

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

$watch(watchExpression, listener, [objectEquality]);

watchExpression => should be either

  1. A string evaluated as expression or
  2. A function called with current scope as a parameter

So here, You should pass your first parameter as a function.

JavaScript Example =>

$scope.$watch (
                function () { return $scope.$location.search(); };
                function (value) { console.log(value); } 
              );

Typescript example =>

this.$scope.$watch (
                     () => { return this.$location.search(); },
                     (value: any) => { console.log(value); }
                   ) ;

This did work for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!