Skip to content

Instantly share code, notes, and snippets.

@twhite96
Forked from oogatta/gist:3fcd96a6e7701bf60080
Last active August 29, 2015 14:22
Show Gist options
  • Save twhite96/a8db44388a63d9da738b to your computer and use it in GitHub Desktop.
Save twhite96/a8db44388a63d9da738b to your computer and use it in GitHub Desktop.
angular legacy url
angular
.module('angular-legacy-url', [])
.factory('AngularLegacyUrl', ['$window', function AngularLegacyUrlFactory($window) {
var getQueries = function (search) {
return search
.replace(/(^\?)/, '')
.split('&')
.reduce(function (sum, item) {
if ( item === '' ) {
return sum;
}
else {
item = item.split('=');
sum[item[0]] = item[1];
return sum;
}
}, {});
};
var getActions = function (pathname) {
return pathname
.replace(/^\//, '')
.replace(/\/$/, '')
.split('/')
.filter(function (action) {
return ( action !== '' );
});
};
return function AngularLegacyUrl(baseAction) {
this.baseAction = ( baseAction ) ? '/' + baseAction : '';
this.actions = getActions($window.location.pathname.replace(new RegExp(this.baseAction), ''));
this.queries = getQueries($window.location.search);
this.toString = function () {
var pathname = '/';
if ( this.actions.length > 0 ) {
pathname += this.actions.join('/') + '/'
}
var search = '';
if ( Object.keys(this.queries).length > 0 ) {
var queries = this.queries;
search += '?' + Object.keys(queries).map(function (key) {
return key + '=' + encodeURIComponent(queries[key]);
}).join('&');
}
return pathname + search;
};
this.set = function () {
$window.location.href = this.baseAction + this.toString();
};
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment