0

AngularJS Routing Dynamically with UI-Router

Previously, I wrote about routing using UI-router. This post demonstrates how to programmatically move from one state to another instead of clicking a set of  ui-sref links.

Software Requirements

UI-Router

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.

Instead of a set of ui-sref links, you’ll have buttons, when clicked, invoke JavaScript functions. These functions are defined in another controller named navByButtonController.

These functions are defined in another controller named navByButtonController.

To move between state, use this:

The name-of-state is any value set for the name property of JSON objects passed to $stateProvider.state(json_object);

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

https://github.com/Turreta/AngularJS-Routing-Dynamically-with-UI-Router

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert