Angular acitve menu item module/directive
A module to add the active class on the elements in a menu
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<div ng-app="myApp">
<div auto-active>
<ul>
<li><a href="#/?some=data">This link points to #/fun1</a>
</li>
<li><a href="#/fun2?some=data">This link points to #/fun2</a>
</li>
<li><a href="#/fun3">This link points to #/fun3</a>
</li>
<li><a href="#/fun4">This link points to #/fun4</a>
</li>
<li><a href="#/fun5?some=data">This link points to #/fun5</a>
</li>
</ul>
</div>
</div>
CSS
li.active {
background-color: red;
}
JavaScript
//this app:
angular.module('myApp', ['autoActive']);
window.location.hash = '#/'; //All hash paths need to start with a /, it happens automaticaly with ngResource and the like...
//the module we are demonstrating:
(function () {
angular.module('autoActive', [])
.directive('autoActive', ['$location', function ($location) {
return {
restrict: 'A',
scope: false,
link: function (scope, element) {
function setActive() {
var path = $location.path();
if (path) {
angular.forEach(element.find('li'), function (li) {
var anchor = li.querySelector('a');
if (anchor.href.match('#' + path + '(?=\\?|$)')) {
angular.element(li).addClass('active');
} else {
angular.element(li).removeClass('active');
}
});
}
}
setActive();
scope.$on('$locationChangeSuccess', setActive);
}
}
}]);
}());