AngularJS allows nested views using UI-Router, enabling multi-level routing in a Single Page Application (SPA).
Why Use Nested Views?
Better structure for complex applications
Allows child routes inside a parent view
Improves code organization and modularity
2. Setting Up ui-router
for Nested Views
Step 1: Include ui-router
in Your Project
CDN Link:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
3. Configuring Nested Routes ($stateProvider
)
var app = angular.module("myApp", ["ui.router"]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state("home", {
url: "/home",
templateUrl: "home.html"
})
.state("home.dashboard", {
url: "/dashboard",
templateUrl: "dashboard.html"
})
.state("home.profile", {
url: "/profile",
templateUrl: "profile.html"
});
});
Explanation:
✔ Parent Route (home
) – Contains child views.
✔ Child Routes (home.dashboard
, home.profile
) – Nested inside home
.
4. Creating HTML Templates for Nested Views
index.html
– Main Layout
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp">
<a ui-sref="home">Home</a> |
<a ui-sref="home.dashboard">Dashboard</a> |
<a ui-sref="home.profile">Profile</a>
<div ui-view></div> <!-- Parent View -->
</body>
</html>
home.html
– Parent View
<h2>Welcome to Home</h2>
<div ui-view></div> <!-- Nested View -->
dashboard.html
– Child View
<h3>Dashboard Content</h3>
<p>This is the Dashboard page inside Home.</p>
profile.html
– Child View
<h3>Profile Content</h3>
<p>This is the Profile page inside Home.</p>
5. Navigation Between Views
Click Dashboard → Loads dashboard.html
inside home.html
Click Profile → Loads profile.html
inside home.html