Integrating UI-Router with AngularJS and RequireJS example for developers

UI-Router is a good module provided by AngularJS for handling routing. In a single page application, routing plays it’s important role and it becomes very difficult to manage different links and it’s related views.

In this example, I will show you step by step process on how you can use angular-ui-router module in your application for managing different states.

Before we start the example, you need to configure RequireJS with AngularJS for modules loading. If you have not done it yet then please go through AngularJS with RequireJS for Developers tutorial on how you can configure RequireJS with AngularJS.

Directory structure for the example is as below



After RequireJS and AngularJS configuration, we can start coding the example.

config/homepage.js
define(['app'], function(app) {
app.config(['$stateProvider', function($stateProvider) {

$stateProvider
.state('home', {
url : '/',
templateUrl : './app/modules/Homepage/views/home.html',
controller : 'HomepageCtrl'
})
.state('about', {
url : '/about',
templateUrl : './app/modules/Homepage/views/about.html',
controller : 'HomepageCtrl'
})
.state('contact', {
url : '/contact',
templateUrl : './app/modules/Homepage/views/contact.html',
controller : 'HomepageCtrl'
});
}]);
console.log("Homepage Config loaded..");
});
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="/AngJSExamples/">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<div class="menu">
<a href="#/">Home | </a>
<a href="#/about">About | </a>
<a href="#/contact">Contact</a></div>
<div ui-view></div>
<script type="text/javascript" src="lib/requirejs/require.js" data-main="app/main"></script>
</body>
</html>
That’s it 🙂

Related Post

Leave a Reply

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