article

Wednesday, January 12, 2022

Angular JS Ui-Router Toggle Active page

Angular JS Ui-Router Toggle Active page

index.html
//index.html
<!DOCTYPE html>
<html ng-app="activemenu">
<head>
	<title>Angular JS Ui-Router Toggle Active page</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/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>
</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
//home.html
<h4>This is the Home Page</h4>
<p><b>Home Tab</b> is active</p>
about.html
//about.html
<h4>This is the About Page</h4>
<p><b>About Tab</b> is active</p>
blog.html
//blog.html
<h4>This is the Blog Page</h4>
<p><b>Blog Tab</b> is active</p>

Related Post