Skip to content

Instantly share code, notes, and snippets.

@alxarch
Created October 8, 2014 11:02
Show Gist options
  • Save alxarch/58a6c5e94cfb1ae1d9e6 to your computer and use it in GitHub Desktop.
Save alxarch/58a6c5e94cfb1ae1d9e6 to your computer and use it in GitHub Desktop.
url filters for angular
urlModule = angularModule "url", ["ngRoute"]
class Url
constructor: (@baseUrl) ->
absoluteUrl: (url) ->
unless url.match /^(\w+:)?\/\//
url = "/#{url}" unless url[0] is '/'
url = "#{@baseUrl}#{url}"
url
buildUrl: (url, params) ->
leftovers = null
for own key, value of params when value?
if -1 is url.indexOf ":#{key}"
leftovers ?= {}
leftovers[key] = value
else
url = url.replace ":#{key}", encodeURIComponent value
if leftovers?
for own key, value of leftovers
url = "#{url}#{if -1 is url.indexOf '?' then '?' else '&'}#{encodeURIComponent key}=#{encodeURIComponent value}"
url
make: (url, params = {}, absolute = no) ->
$injector = angular.injector()
state =
url: url
params: params
absolute: absolute
if angular.isFunction @preProcess
$injector.invoke @preProcess, state
unless state.done
state.url = @buildUrl state.url, state.params
if angular.isFunction @postProcess
$injector.invoke @postProcess, state
unless state.done
if state.absolute
state.url = @absoluteUrl state.url
state.url
class UrlProvider
baseUrl = ($location, basePath, noProtocol) ->
parts = []
unless noProtocol
parts.push $location.protocol()
parts.push ":"
parts.push "//"
parts.push $location.host()
port = $location.port()
if port
parts.push ":#{port}"
if basePath
parts.push basePath
parts.join("").replace /\/$/, ''
constructor: ->
@$get = ($location, $route) =>
url = new Url
url.routeIdentifier = @routeIdentifier or "id"
url.baseUrl = baseUrl $location, @basePath, @noProtocol
url.preProcess = @preProcess
url.postProcess = @postProcess
url
urlModule.provider "$url", UrlProvider
urlModule.filter "urlFor", ($url, $route) ->
(value, params, absolute) ->
for own path, route of $route.routes when route[$url.routeIdentifier] is value
return $url.make path, params, absolute
value
urlModule.filter "url", ($url) ->
(url, params, absolute) -> $url.make url, params, absolute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment