-
-
Save twhite96/a8db44388a63d9da738b to your computer and use it in GitHub Desktop.
angular legacy url
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
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