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?
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 ...);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With