Implementing nested states using UI-Router

Loading

In AngularJS, UI-Router allows you to define nested states to create structured, maintainable, and scalable applications. Nested states help in managing multiple views inside a parent view efficiently.


1️⃣ Why Use Nested States?

Organized UI structure
Encapsulation of features
Better state management
Improved maintainability


2️⃣ Installing UI-Router

To use UI-Router, include it in your project:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>

Or install via npm:

npm install @uirouter/angularjs --save

3️⃣ Configuring UI-Router in AngularJS

Add ui.router as a dependency in your module:

var app = angular.module('MyApp', ['ui.router']);

4️⃣ Defining Parent and Nested States

Nested states are defined using the dot (.) notation.

Example: Parent and Child States

app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeCtrl'
})
.state('home.dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl'
})
.state('home.profile', {
url: '/profile',
templateUrl: 'profile.html',
controller: 'ProfileCtrl'
});

$urlRouterProvider.otherwise('/home');
});

5️⃣ Creating Parent and Child Views

Parent Template (home.html)

<h2>Home Page</h2>
<a ui-sref="home.dashboard">Go to Dashboard</a>
<a ui-sref="home.profile">Go to Profile</a>

<div ui-view></div> <!-- This will be replaced by child views -->

Child Templates

Dashboard (dashboard.html)

<h3>Dashboard Page</h3>

Profile (profile.html)

<h3>Profile Page</h3>

6️⃣ Navigating Between States

Use the ui-sref directive for navigation:

<a ui-sref="home.dashboard">Dashboard</a>
<a ui-sref="home.profile">Profile</a>

Alternatively, navigate programmatically in controllers:

app.controller('HomeCtrl', function($scope, $state) {
$scope.goToDashboard = function() {
$state.go('home.dashboard');
};
});

7️⃣ Handling URL Parameters in Nested States

To pass parameters, modify the state definition:

.state('home.profile', {
url: '/profile/:userId',
templateUrl: 'profile.html',
controller: 'ProfileCtrl'
})

Access parameters in the controller:

app.controller('ProfileCtrl', function($scope, $stateParams) {
$scope.userId = $stateParams.userId;
});

Summary

  • Use UI-Router (ui.router) for better state management.
  • Define nested states using the dot (.) notation.
  • Use ui-view in parent templates to load child views dynamically.
  • Use ui-sref for smooth navigation.
  • Pass URL parameters to child states when needed.

Leave a Reply

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