Angular decorator: Add case insensitive urls to all routes

Use angular's provider decorator to add case insensitive behaviour

Posted by Aditya Pratap Singh on July 6, 2015

Angular’s provider is a way to add custom behaviour to the service instances. A nice explanation of difference between between provider, factory and service is given here by Misko Hevery.

Decorators (provider.decorate()) is a way to augment the provider with additional behaviour while configuring module, even before injecting it.

A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. -

In order to make the url for a given path as case insensitive, angular router provides us with a property caseInsensitiveMatch which can be used as below to make given path case insensitive.

But the above approach is not very efficient if we want to make all the routes case-insensitive. Here comes decorators to the rescue. Using the provider.decorate() we can wrap the $route service provider to make the url case insensitive. Below decorator code snippet makes the routes case-insensitive.

Step wise description:

  1. We have created a basic angular app with config block
  2. Within the config function, we have injected the $provide service which is used to decorate the route service using .decorate() method on it
  3. The .decorate() function accepts 2 parameters: First parameter is name of service we want to decorate, in this case $route. Second parameter extendRouteProvider is a function which accepts parameter $delegate which is a delegate for service passed in first parameter.
  4. Within the extendRouteProvider function we have iterated over all the routes and updated 2 properties:
    1. route.regexp: make the regular expression for the path case insensitive
    2. route.caseInsensitiveMatch: Make the case insensitive matching property as true

That’s it! All the routes now become case insensitive and will work just fine for both cases of path values.