0

I am creating a sidebar based off of this one

http://plnkr.co/edit/xzcjStdvmkI2rpfMzLjI?p=preview found from this tutorial

However I want to keep the selection active once the link is clicked. I've tried adding data-toggle, but that seems to work for nav-pills instead of navbar. I also found an is-active-nav directive that I've attempted to implement:

angular.module('sidebarmodule')
    .directive('isActiveNav', ['$location', function ($location) {
    return {
        restrict: 'A',
        link: function (scope, element) {
            scope.location = $location;
            scope.$watch('location.path()', function (currentPath) {
                if ('/#' + currentPath === element[0].attributes['href'].nodeValue) {
                    element.parent().addClass('active');
                } else {
                    element.parent().removeClass('active');
                }
            });

        }
    };
}]);

That I call in the sidebar template like so:

<li> <a is-active-nav href="#">Link1</a> </li>

Another approach I tried is in my controller adding

$scope.isActive = function (viewLocation) { return viewLocation === $location.path(); }; 

and then adding to the template:

<li ng-class="{ active: isActive('/importinvoice')}"><a href="#/firstlink">First Link</a></li>

However, nothing I do will keep the sidebar elements highlighted after navigating to that page. I am trying to keep out of jQuery as I want it to be an AngularJS solution only.

I tried most of the solutions from this stackoverflow answer but can't get any of them to work on the plunker.

Community
  • 1
  • 1
jenryb
  • 2,017
  • 12
  • 35
  • 72

1 Answers1

1

You are on the right track:

The isActive function for each list element needs to pass in the parameter that matches it's href - so in your given example, it should be:

<li ng-class="{ active: isActive('/firstlink')}"><a href="#/firstlink">First Link</a></li>

You also need to add in the style for the active class in the CSS. I'm not sure if you have done this already as the plunkr you provided is incomplete.

See my Plunkr here: http://plnkr.co/edit/zE6sXEn4wHJufOlnNeld

james00794
  • 1,137
  • 7
  • 14
  • Silly me forgot to add in the style for the active class. Thanks a lot for your working Plunkr! – jenryb Mar 15 '16 at 15:55