Angular Dynamic Query String
Dynamically manipulate the query string parameters using the Angular.js $location.search() method.
by Josh Carroll
HTML
<div ng-controller="SearchCtrl">
<div class="location">
<span>$location.search()</span>
<code>{{urlPart('search')}}</code>
</div>
<div class="location">
<span>$location.url()</span>
<code>{{urlPart('url')}}</code>
</div>
<div class="param" ng-repeat="term in terms">
<span>{{term.name}}</span>
<input type="text" ng-model="term.value" ng-change="changeSearchTerm()" />
<input type="checkbox" ng-model="term.isActive" ng-change="changeSearchTerm()" />
</div>
</div>
CSS
.location {
padding:2px;
margin-bottom:5px;
}
.location span, .param span{
display:inline-block;
text-align:right;
width:150px;
font-weight:bold;
font-size:1.2em;
}
.location code{
padding: 5px;
display:inline-block;
width:400px;
background-color:#E0E0E0;
}
JavaScript
(function () {
var myModule = angular.module('blah', []);
function SearchCtrl($scope, $location, $log){
var terms = [{
name: "genre",
value: "drama",
isActive: false
}, {
name: "actor",
value: "DeNiro",
isActive: false
}, {
name: "year",
value: 1983,
isActive: false
}];
$scope.terms = terms;
$scope.urlPart = function(partName){
return $location[partName]();
};
$scope.changeSearchTerm = function () {
var activeTerms = {};
terms.forEach(function (term) {
if (term.isActive) {
activeTerms[term.name] = term.value;
}
});
$location.search(activeTerms);
$log.log(activeTerms);
};
}
SearchCtrl.$inject = ['$scope', '$location', '$log'];
myModule.controller('SearchCtrl', SearchCtrl);
}());