2

I have a navbar with two links:

<nav>
  <a ng-link="['Route1']">Route 1</a>
  <a ng-link="['Route2']">Route 2</a>
</nav>

I would like to highlight the link associated with the active route. Essentially, I would like to add a class called router-link-active to one of the two links above. What's the easiest way to do this for the new Angular 1 Component Router?

Naresh
  • 23,937
  • 33
  • 132
  • 204

2 Answers2

0

UPDATE:

The ComponentRouter for Angular 1 is now deprecated. For using angular 1.5 components, it's recommended to use the well-known ui-router.


Angular 1 Component Router automatically adds the ng-link-active class to active ng-links.

If your version isn't adding this automatically, you are probably using an outdated version of the Component Router. I've been using this version which is a more recent compilation rather than the one stated on the docs (which is 0.2.0).

Let's hope they get it production-ready soon.

Daniel Higueras
  • 2,404
  • 22
  • 34
-1

I didn't want to go with a "non-official" release, so i created my own directive that adds ng-link-active (see below).

Notes:

  1. You need to make sure that "path" and "name" properties in your routes are the same (other than "/", ":" and capitalization which are ignored) - I don't love this limitation but it's OK for me until a fixed version is released.
  2. This is in ES6 but should be clear enough even if you write your code in ES5.

    export const isActive =
    /*@ngInject*/
    function ($location) {
        return {
            restrict: 'A',
            link: linkFunc,
        };
    
        /**
         * Adds active class to ng-link matching current route
         *
         * @param {Object} scope
         * @param {Object} element
         * @param {Object} attrs
         *  @param {String} attrs.ngLink
         *  @param {Function} attrs.$addClass
         *  @param {Function} attrs.$removeClass
         */
        function linkFunc (scope, element, attrs) {
    
            const activeClass = 'ng-link-active';
    
            scope.$watch(getUrl, setClass);
    
            function getUrl () {
                return $location.url();
            }
    
            function setClass () {
                // eg "/books/..." -> 'books'
                const pathName = $location.url().split('/')[1].toLowerCase();
                // eg "['Books']" -> 'books'
                const routeName = attrs.ngLink ? (attrs.ngLink.split('\'')[1].toLowerCase()) : '';
    
                if (pathName === routeName) {
                    attrs.$addClass(activeClass);
                    return;
                }
                attrs.$removeClass(activeClass);
            } // setClass
    
        } // linkFunc
    
    };
    
yar1
  • 1,331
  • 2
  • 15
  • 26