Adding Angular directive using decorator

梦想的初衷 提交于 2019-12-24 13:48:49

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/34686823/adding-angular-directive-using-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!