Angular using input select filter to update route?

I have set up an application in which the list of products can be filtered by color using select input, I also have a $routeprovider that passes this color parameter to the page if it is present in the URL.

Now I want to update the url when the selection box is changed. How to associate a selection change with a route?

+7
source share
2 answers

select has the undocumented ng-change parameter, which you can use to call the 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 ...); } } 
+12
source

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 would suggest using $location.search : you can just change the parameter you want, and it works a little less, since you do not need to know the whole path in your controller.

So, suppose you have a <select> element:

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

You can use $watch to view your associated value and update your $location.search by pointing it to null if the color is undefined or otherwise false (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 establish a two-way binding between the search parameter and the local model so that the changes are 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.

+4
source

All Articles