Last active
August 29, 2015 14:15
-
-
Save pjsvis/6c2e7970551fc58bf0ff to your computer and use it in GitHub Desktop.
Angular Service to Build a URL with Query Params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NOTE: Build a url with query params | |
angular.module('app').factory('UrlBuilder', function () { | |
function sortedKeys(obj) { | |
var keys = []; | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
keys.push(key); | |
} | |
} | |
return keys.sort(); | |
} | |
function forEachSorted(obj, iterator, context) { | |
var keys = sortedKeys(obj); | |
for (var i = 0; i < keys.length; i++) { | |
iterator.call(context, obj[keys[i]], keys[i]); | |
} | |
return keys; | |
} | |
function buildUrl(url, params) { | |
if (!params) return url; | |
var parts = []; | |
forEachSorted(params, function (value, key) { | |
if (value == null || value == undefined) return; | |
if (angular.isObject(value)) { | |
value = angular.toJson(value); | |
} | |
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); | |
}); | |
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); | |
} | |
return { | |
buildUrl: buildUrl | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment