Upon reflection, a solution has been found.
The key here is to have a single object in the $scope (named $scope.filter) to store all form input values, making it easy to manage without needing to modify the controller when adding new inputs to the form.
angular.module('myApp')
.controller('myController', ['$scope', '$http' '$location', function($scope, $http, $location) {
$scope.filter = {};
$scope.init = function(){
// $location.search() will return an object with the params,
// those values are set to $scope.filter, and the filter values are initialized in case of direct link to the page
$scope.filter = $location.search();
$scope.executeFilter();
};
// Fetching the desired data and presenting it,
// using the filter values as a Json in that server call
$scope.executeFilter = function(){
// Updating the url with the current filter values,
// allowing users to copy the relevant url for later use
$location.search($scope.filter);
var paramsAsJson = angular.toJson($location.search());
$http.post('my-url', paramsAsJson).success(function(data) {
// update view
});
};
$scope.init();
}]);
Here is an example view:
<form ng-submit="executeFilter()">
<input name="some_text" type="text" ng-model="filter.some_text">
<!-- more inputs here -->
// Supports multiple select
// (passes a json with array of selected values to the server)
<select multiple="multiple" name="some_options" ng-model="filter.some_options">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<button>Filter</button>
</form>
If a user opens this page with a URL like www.my-url.com/?some_text=foo
, the input with the directive ng-model="filter.some_text"
will automatically contain 'foo' upon page load, triggering a server request with that parameter.