IsaiahPacheco
9/15/2014 - 2:09 AM

Sets anchor tag class to "active" when href attribute matches current $location.path() only using jqLite methods

Sets anchor tag class to "active" when href attribute matches current $location.path() only using jqLite methods

// JQuery Optional, built with Angular jqLite methods only

// HTML example use
// <ul nav-tabs>
// 	<li><a href="/absolute/or/relative path"> Menu Item </a></li>
// </ul>

app.
    directive('navTabs', ['$location',
    function ($location) {
            return {
                restrict: 'A',
                link: function(scope, element) {
                    var tabs = element.children(),
                    tabMap = {};

                    for(var i = 0; i < tabs.length; i ++) {
                        var li = angular.element(tabs[i])
                        tabMap[li.find("a").attr('href')] = li;
                    };

                    scope.$on('$locationChangeSuccess', function() {
                        element.find("li").removeClass("active");
                        tabMap[$location.path()].addClass("active");
                    });
            }
        }
    }]);