Angular JS Toggle Active Class on Path Change using Ui-Router
Submitted by nurhodelta_17 on Tuesday, January 23, 2018 - 21:51.
Getting Started
I've used CDN for Bootstrap, Angular JS and Ui-Router so you need internet connection for them to work.index.html
This is the main page 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 scripts. .config is where we set the routes of our app and in .controller, we have our active function which returns active whenever the passed parameter is the same as the current path.- var app = angular.module('app', ['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' : '';
- }
- });
Creating our Paths
The ff are the templates for the paths in this tutorial. home.html about.html blog.html That ends this tutorial. Happy Coding :)Add new comment
- 26 views