AngularJS Routing with UI-Router

Previously I wrote about routing using ngRoute. This post demonstrates how to implement routing using UI-Router, a rather flexible routing solution with nested views in AngularJS unlike ngRoute.

Software Requirements


Before UI-Router can be used, you have to download it together with the main AngularJS library. Then include them in the main HTML file along with your AngularJS codes.

To navigate to those routes, provide ui-sref links to them.

Define Routes

The next thing to do is to define a number of routes using $stateProvider in the config function in myapp.js.

We use $urlRouterProvider to set an initial or default URL.

UI-View Directive

The uiView directive as shown in the code snippet below is where the contents from the templateUrls get displayed per selected route, e.g., '/second'. The section is updated when the route changes.

Testing our SPA

Download the codes


Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert