Defining abstract states in UI-Router

Loading

In UI-Router, an abstract state is a parent state that cannot be directly activated but provides a base structure for child states. Abstract states help in code organization, reducing redundancy, and enforcing consistent layouts across multiple views.


1️⃣ Why Use Abstract States?

Encapsulates common layouts & functionalities
Prevents direct access to parent states
Improves code maintainability
Encourages reusability


2️⃣ Declaring an Abstract State

An abstract state is defined by setting abstract: true in its configuration.

Example: Abstract State for Dashboard Layout

app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dashboard', {
url: '/dashboard',
abstract: true, // Prevents direct access
templateUrl: 'dashboard-layout.html'
})
.state('dashboard.home', {
url: '/home',
templateUrl: 'dashboard-home.html',
controller: 'HomeCtrl'
})
.state('dashboard.profile', {
url: '/profile',
templateUrl: 'dashboard-profile.html',
controller: 'ProfileCtrl'
});

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

3️⃣ Creating the Parent (Abstract) Template

Since dashboard is abstract, it should contain a common layout and a ui-view for child states.

Abstract Parent Template (dashboard-layout.html)

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

<!-- Child views will be injected here -->
<div ui-view></div>

4️⃣ Creating Child State Templates

Home View (dashboard-home.html)

<h3>Welcome to Dashboard Home</h3>

Profile View (dashboard-profile.html)

<h3>User Profile Page</h3>

5️⃣ Preventing Direct Navigation to Abstract States

Trying to navigate to an abstract state (dashboard) directly will not work. Instead, redirect users to a default child state using $urlRouterProvider:

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

6️⃣ Accessing Data from Abstract States

You can define controllers in abstract states and share data with child states.

app.controller('DashboardCtrl', function($scope) {
$scope.title = "User Dashboard";
});

Then use it in the parent template (dashboard-layout.html):

<h2>{{ title }}</h2>

Child templates will inherit the scope.

Leave a Reply

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