1

I'm using Angular 1.4.8 with Angular UI. What I'm trying to do is decorate the ui-sref directive so it will highlight a menu element (by setting the CSS class 'active') if the current $state.name matches the ui-sref state.

I test to see if the element is descendent from my nav header, and if it is, I want to add an ngClass attribute to the element. For right now, I just want to make them all highlight; I can add the test for matching the state later. The true will be replaced with the actual test. Right now I just want the active class set

.config(['$provide', ($provide: angular.auto.IProvideService) => {
    return $provide.decorator('uiSrefDirective', [
        '$delegate', ($delegate) => {
            var originalUiSref = $delegate[0];
            var originalUiSrefLink = originalUiSref.link;

            originalUiSref.compile = () => (scope, element, attrs, uiSref) => {
                var topBar = $('nav.top-bar');
                if (topBar.length > 0 && $.contains(topBar[0], element[0])) {
                    element.parent().attr('ng-class', '{ active: true }');    
                }

                originalUiSrefLink.call($delegate, scope, element, attrs, uiSref);
            };

            return $delegate;
        }
    ]);
}])

The original DOM element:

<a ui-sref="requests">Requests</a>

After adding the decorator, this is what I see in my browser's DOM:

<a ui-sref="requests" ng-class="{ active: true }" href="/requests">Requests</a>

Great! I can see the added attribute in the DOM, but my browser is ignoring it. It's almost as though it's getting added after Angular scans the DOM for directives. If I change the code to:

element.parent().addClass('active');

... then it works fine. What am I doing wrong?

3
  • 1
    what is wrong with ui-sref-active ? angular-ui.github.io/ui-router/site/#/api/… Commented Jan 8, 2016 at 22:29
  • I just didn't know about it. Thanks! Commented Jan 8, 2016 at 22:59
  • I consider that an answer to this question. If you submit it as an answer, I'll accept it. Commented Jan 8, 2016 at 23:00

1 Answer 1

0

Amy you do not need to implement this directive as angular-ui in fact already have it, please check ui-sref-active

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.