AngularJS Tutorial: ui-router example

Since ui-router is one of the most useful features that angular can provide I decided to write this tutorial just to show how to use it, I’m going to create a very simple application that illustrates how to create templates using ui-router states.

After donwloading angular.min.js and angular-ui-router.min.js let’s create our index.html and include both:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html ng-app="uiRouterExample">
    <head>
        <title>ui-router example</title>
        <script src="js/angular.min.js" type="text/javascript"></script>
        <script src="js/angular-ui-router.min.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
    </head>
    <body>
        <div ui-view></div>
    </body>
</html>

This file will be our template, it will be the same no matter the state, note that inside the body I have a div with the ui-view attribute, that’s where our states will be included.

With the index.html ready let’s create the app.js:

1
2
3
4
5
6
7
8
9
10
11
var app = angular.module('uiRouterExample', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state("state1", {
        url: "/state1",
        templateUrl: "states/state1.html"
    }).state("state2", {
        url: "/state2",
        templateUrl: "states/state2.html"
    });
    $urlRouterProvider.otherwise("/state1");
});

I tried to make this code as simple as possible, I’ve just created 2 states named ‘state1′ and ‘state2′, each one of them receives an object containing the attributes ‘url’ and ‘templateUrl’, the first one is the path we’re going to type on our browser to call the states, and the second is the html file that will be displayed when the state is called.

Lastly I’m making state1 the default state by passing its path to $urlRouterProvider.otherwise function, this way when the application is first loaded the state1 will be called by default.

Now let’s take a look at out state1.html and state2.html:

1
2
3
4
5
6
7
8
9
<!--state1.html-->
This is the State1
<br />
<a ui-sref="state2">Go to state2</a>
 
<!--state2.html-->
This is the State2
<br />
<a ui-sref="state1">Go to state1</a>

If you run your project, since state1 is your default state, you’re going to see the state1.html rendered on your screen, and if you click on the link you’re going to be redirected to state2.

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>