Skip to content

Instantly share code, notes, and snippets.

@andyford
Created August 15, 2014 21:43
Show Gist options
  • Select an option

  • Save andyford/a157a2950bb807ab549b to your computer and use it in GitHub Desktop.

Select an option

Save andyford/a157a2950bb807ab549b to your computer and use it in GitHub Desktop.
Current/Active nav in AngularJS
/*
* NavMainCtrl
* inspired by: http://stackoverflow.com/a/18894679/17252
*/
.controller('NavMainCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.isCurrentPath = function (paths) {
// if we get a string instead of an array, turn into array with single string element
if (_.isString(paths)) { paths = [paths]; }
var i, len = paths.length;
for (i = 0; i < len; i += 1) {
if ($location.path().indexOf(paths[i]) === 0) {
return true;
}
};
return false;
};
}]);
// HTML example (with string or array)
// <ul class="nav navbar-nav" ng-controller="NavMainCtrl">
// <li ng-class="{ active: isCurrentPath('/dashboard') }"><a href="/app#/dashboard">dashboard</a></li>
// <li ng-class="{ active: isCurrentPath([ '/projects', '/project' ]) }"><a href="/app#/projects">projects</a></li>
// <ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment