AngularJS Example: menu active link
by manoj
HTML
<link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.4/angular.min.js"></script>
<script src="http://code.angularjs.org/1.3.0-beta.4/angular-route.js"></script>
<div ng-controller="MainCtrl" ng-app=app>
<span class="label label-danger">Without bs-active-link</span>
<br>
<ul class="nav nav-pills">
<li><a href="#/home">Home</a>
</li>
<li><a href="#/list">List</a>
</li>
<li><a href="#/settings">Settings</a>
</li>
</ul>
<br><br>
<span class="label label-success">With bs-active-link</span>
<ul class="nav nav-pills" bs-active-link>
<li><a href="#/home">Home</a>
</li>
<li><a href="#/list">List</a>
</li>
<li><a href="#/settings">Settings</a>
</li>
</ul>
<hr>
<ng-view>Loading...</ng-view>
<!-- Inline Templates (Partials) -->
<script type=text/ng-template id=home.html>
Home View
</script>
<script type=text/ng-template id=list.html>
List View
</script>
<script type=text/ng-template id=settings.html>
Settings View
</script>
</div>
JavaScript
angular.module('app', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'home.html',
controller: MainCtrl
}).
when('/list', {
templateUrl: 'list.html',
controller: MainCtrl
}).
when('/detail/:itemId', {
templateUrl: 'detail.html',
controller: MainCtrl
}).
when('/settings', {
templateUrl: 'settings.html',
controller: MainCtrl
}).
otherwise({
redirectTo: '/home'
});
}]);
angular.module('app')
.directive('bsActiveLink', ['$location', function ($location) {
return {
restrict: 'A', //use as attribute
replace: false,
link: function (scope, elem) {
//after the route has changed
scope.$on("$routeChangeSuccess", function () {
var selectors = ['li > [href="/#' + $location.path() + '"]',
'li > [href="#' + $location.path() + '"]', //html5: false
'li > [href="' + $location.path() + '"]']; //html5: true
$(elem).find(selectors.join(',')) //find the matching link
.parent('li').addClass('active') //add active class to the matching element
.siblings('li').removeClass('active'); //remove it from the sibling elements
});
}
}
}]);
/* Controllers */
function MainCtrl($scope) {
}