Intro to Angular UI Router
For the uninitiated, behold angular-ui-router
If you’re like me you’ve used ui-router before with angular.js. Your applications probably look something like this:
templates/main.html gets rendered in
<div ui-view></div> of index.html. It’s functional and it works.
To show off getting data and some more advanced features of ui-router I fired up an express server in server.js that serves index.html and a “posts” API.
For a really basic implementation, getting the posts:
Once the controller is instantialized it will fire a request to the appropriate endpoint. Once that request is returned with data the data will populate the
posts array on the scope.
In templates/main.html we render the posts to the screen with a simple
This is a pretty simple implementation of routing with angular.js but it works. Recently I’ve learned some extra tricks I’d like to share.
The issue with this, having the call in the controller, is that there will be a small delay from when the page loads to when the page is actually populated with data from the server. ui-router has a solution - resolve.
From the docs:
You can use resolve to provide your controller with content or data that is custom to the state. If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the
$stateChangeSuccessevent is fired.
Using the resolve property in our state:
Resolve makes our controller more simple:
The advantage of this approach is that
posts is gauranteed to be available when the controller for the route is instantialized.
So we have a lists of posts. Each post uses ng-href so that we can use scope properties in the url path. Let’s define that URL route:
The controller is light again:
And the view is simple:
/#/ for the ng-href is ugly. ui-router uses states, so we can use ui-sref instead. ui-sref directs to a state instead of a url route. Our list of posts updates to:
This way if we change the endpoint url for viewing a post we only change it in the routes definition, not all over our html.
For instance a simple back button on the post page:
<div class='btn btn-primary' ng-click='goBack()'>< Back</div>
and the method is defined in
Now we can see an individual post and easily navigate back to the home state. The url is persistent, meaning you can bookmark it and refresh the page and see the same thing. We get that for free with ui-router, where it takes extra code in a framework like Backbone.
We’ll define a child state:
Then update templates/main.html:
Now when you click on preview you’ll see the post’s description. There are some more tricks with ui-router like using abstract states and declaring multiple named views. This is an introduction to ui router and will serve you moving forward. Happy coding!
Also check out the SOURCE CODE.
Also you can follow me on twitter!