Skip to content

Instantly share code, notes, and snippets.

@oogatta
Created May 31, 2015 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oogatta/3fcd96a6e7701bf60080 to your computer and use it in GitHub Desktop.
Save oogatta/3fcd96a6e7701bf60080 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