article

Wednesday, January 12, 2022

Angular JS Ui-Router Toggle Active page

Angular JS Ui-Router Toggle Active page

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//index.html
<!DOCTYPE html>
<html ng-app="activemenu">
<head>
    <title>Angular JS Ui-Router Toggle Active page</title>
    <meta charset="utf-8">
</head>
<body>
<nav ng-controller="mainCtrl" class="navbar navbar-default">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Cairocoders</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li ng-class="active('/home')"><a ui-sref="home">Home</a></li>
                <li ng-class="active('/about')"><a ui-sref="about">About</a></li>
                <li ng-class="active('/blog')"><a ui-sref="blog">Blog</a></li>
            </ul>
        </div>
    </div>
</nav>
<div class="container">
    <div ui-view></div>
</div>
<script>
var app = angular.module('activemenu', ['ui.router']);
 
app.config(function($stateProvider, $urlRouterProvider) {
     
    $urlRouterProvider.otherwise('/home');
     
    $stateProvider
 
        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })
               
        .state('about', {
            url: '/about',
            templateUrl: 'about.html',
             
        })
 
        .state('blog', {
            url: '/blog',
            templateUrl: 'blog.html',
        });
         
});
 
app.controller('mainCtrl', function($scope, $location){
    $scope.active = function(path){
         return ($location.path() === path) ? 'active' : '';
    }
});
</script>
</body>
</html>
home.html
1
2
3
//home.html
<h4>This is the Home Page</h4>
<p><b>Home Tab</b> is active</p>
about.html
1
2
3
//about.html
<h4>This is the About Page</h4>
<p><b>About Tab</b> is active</p>
blog.html
1
2
3
//blog.html
<h4>This is the Blog Page</h4>
<p><b>Blog Tab</b> is active</p>

Related Post