I'm trying to find a way to implement route aliases in Angular.js using ui-router
.
Let's say I have a state with the url article/:articleId
and I want to have /articles/some-article-title
redirected (internally) to /article/76554
without changing the browser location.
Could this be done with ui-router
?
I. Doubled state mapping (reuse of controller, views)
NOTE: This is original answer, showing how to solve the issue with two states. Below is another approach, reacting on the comment by Geert
There is a plunker with working example. Say we have this two objects (on a server)
And we would like to use URL as
Then we can create this state definitions:
As we can see, the trick is that the Controller and the Template (templateUrl) are the same. We just ask the Service
ArticleSvc
togetById()
orgetByTitle()
. Once resolved, we can work with the returned item...The plunker with more details is here
II. Aliasing, based on native
UI-Router
functionalityNote: This extension reacts on Geert appropriate comment
So, there is a
UI-Router
built-in/native way for route aliasing. It is called$urlRouterProvider - .when()
I created working plunker here. Firstly, we will need only one state defintion, but without any restrictions on ID.
We also have to implement some mapper, converting title to id (the alias mapper). That would be new Article service method:
And now the power of
$urlRouterProvider.when()
That's it. This simple implementation skips error, wrong title... handling. But that is expected to be implemented anyhow... Check it here in action