Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Search Change Event

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!

like image 717
Christian Stewart Avatar asked Dec 03 '22 00:12

Christian Stewart


2 Answers

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).

like image 91
Maxim Grach Avatar answered Dec 05 '22 13:12

Maxim Grach


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;
});
like image 43
Satpal Tanan Avatar answered Dec 05 '22 14:12

Satpal Tanan