4

I need an event like $routeChangeSuccess but for the $location.search() variable. I am calling $location.search('newview'), and need a way to know when it changes.

Thanks!

Christian Stewart
  • 15,217
  • 20
  • 82
  • 139
  • possible duplicate of [AngularJs $watch on $location.search doesn't work when reloadOnSearch is false](http://stackoverflow.com/questions/15093916/angularjs-watch-on-location-search-doesnt-work-when-reloadonsearch-is-false) – Léo Lam Feb 19 '15 at 19:37

2 Answers2

15

You should use $scope.$watch:

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

See more about $watch in Angular docs.

If you are just looking for the addition of 'newview', to the query string the above code will work.

i.e. from http://server/page to http://server/page?newvalue

However, if you are looking for a change in 'newview' the above code will not work.

i.e from http://server/page?newvalue=a to http://server/page?newvalue=b

You will need to use the 'objectEquality' param to the call to $watch. This causes $watch to use value equality, instead of object reference equality.

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

Notice the addition of 3rd param (true).

Mike Ohlsen
  • 1,900
  • 12
  • 21
Maxim Grach
  • 4,300
  • 2
  • 20
  • 19
  • Ah, you can actually use a function in watch. Thanks. – Christian Stewart Feb 14 '13 at 20:23
  • make sure you use the "objectEquality" param (3rd argument) in the call to $watch. Without this, it checks for object reference equality, not by value. The $watch would works if 'newview' was added to the querystring, but would not work if you changed the value of 'newview' – Mike Ohlsen Apr 23 '14 at 13:34
  • couldn't you just do: $scope.watch($location.search, function() { ... }) – Bob Monteverde Sep 11 '14 at 22:40
  • 1
    No, you couldn't. The first argument in $watch function is called with the $scope as first argument and the $location.search method, in this case, expect no argument – csbenjamin Sep 14 '14 at 14:40
2

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;
});
Satpal Tanan
  • 1,108
  • 7
  • 17