Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, using select input filter to update route?

I have my app set up where a list of products can be filtered by colour using a select input, I also have the $routeprovider passing this colour param to the page if it is present in the url.

What I want to do now is update the url / route when the select box is changed. How do I bind the change of the select to the route?

like image 467
Tim Webster Avatar asked Feb 06 '13 13:02

Tim Webster


2 Answers

select has an undocumented ng-change parameter that you can use to call a function to set $location.path:

<select ... ng-model="color" ng-change="updatePath()">

Controller:

function MyCtrl($scope, $location) {
    $scope.updatePath = function() {
       $location.path(... use $scope.color here ...);
    }
}
like image 130
Mark Rajcok Avatar answered Oct 04 '22 03:10

Mark Rajcok


Your <select> element will be bound to a model with ng-model, which you can $watch and use to update either $location.path or $location.search. Personally, I'd suggest using $location.search: you can change just the parameter you want, and its a bit less work since you don't have to have knowledge of the entire path in your controller.

So assuming you have a <select> element like this:

<select ng-model="selectedColor" ng-options="color for color in colors">

You can use $watch to watch your bound value and update your $location.search, making sure to set it to null if color is undefined or otherwise falsey (this clears the search parameter):

$scope.$watch('selectedColor', function (color) {
    if (color) {
      $location.search('color', color); 
    } else {
      $location.search('color', null);
    }
});

You might want to set up a two-way binding between the search parameter and your local model so that changes will be reflected in your <select>:

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

Then it's just a matter of accessing $routeParams.color in your routed controller.

See this plunk for a complete working example.

like image 33
Scott Baldwin Avatar answered Oct 04 '22 03:10

Scott Baldwin