Angular JS Toggle Active Class on Path Change using ng-Route
Submitted by nurhodelta_17 on Tuesday, January 23, 2018 - 23:10.
Getting Started
I've used CDN for Bootstrap, Angular JS and Angular Route so you need internet connection for them to work.index.html
This is the main view of our app.- <!DOCTYPE html>
- <html ng-app="app">
- <head>
- <meta charset="utf-8">
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body ng-controller="mainCtrl">
- <nav 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">
- </button>
- </div>
- <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
- <ul class="nav navbar-nav">
- </ul>
- </div>
- </div>
- </nav>
- <div class="container">
- </div>
- </body>
- </html>
app.js
This contains our angular js script. .config is where we setup the each of our path and .controller is where active function is found.- var app = angular.module('app', ['ngRoute']);
- app.config(function($routeProvider){
- $routeProvider
- .when('/', {
- templateUrl: 'home.html'
- })
- .when('/about', {
- templateUrl: 'about.html'
- })
- .when('/blog', {
- templateUrl: 'blog.html'
- })
- .otherwise({
- redirectTo: '/'
- });
- });
- app.controller('mainCtrl', function($scope, $location){
- $scope.active = function(path){
- return ($location.path() === path) ? 'active' : '';
- }
- });
Creating our Path Templates
The ff. are the template for our route. home.html about.html blog.html That ends this tutorial. Happy Coding :)Add new comment
- 33 views