Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My routeProvider for route has reloadOnSearch set to false :

 $routeProvider      .when(         "/film/list",          {           templateUrl: '/film/list.html',            controller: FilmListController,           reloadOnSearch: false           }            ....    ) 

I did this because I don't want the whole controller to be reloaded after query string changes, but I still use it and the url looks like this: film/list?sort=isbn&order=asc&offset=0. Now whenever query string changes I want to call a function from my controller. So I tried to set up a $watch in the controller:

$scope.location = $location; $scope.$watch( 'location.search()', function( search) {         $scope.list();  }); 

But this doesn't work. If I set $watch to watch changes of an individual parameter of a query string, then it works. But I don't want to set $watch for every parameter of my query string. The solution I use now is this:

$scope.location = $location; $scope.$watch( 'location.url()', function( url ) {     if($location.path() == '/film/list')         $scope.list();  }); 

So instead of watching for the search, I watch the whole url, and then I check if the path is the one I set in routeProvider to conditionally call the function. What I don't like about this solution is that I have to explicilty type the value for $location.path to be matched.

Can anyone suggest a better solution, and perhaps explain me why is $watch not working for $location.search() ?

like image 946
MBozic Avatar asked Feb 26 '13 16:02

MBozic


1 Answers

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(); }) 
like image 134
Le Duc Duy Avatar answered Sep 27 '22 22:09

Le Duc Duy