使用装饰器添加 Angular 指令 [英] Adding Angular directive using decorator

查看:26
本文介绍了使用装饰器添加 Angular 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Angular 1.4.8 与 Angular UI 一起使用.我想要做的是装饰 ui-sref 指令,以便它会突出显示菜单元素(通过设置 CSS 类活动"),如果当前 $state.name 匹配 ui-sref 状态.

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.

我测试该元素是否是我的导航标头的后代,如果是,我想向该元素添加一个 ngClass 属性.现在,我只想让它们都突出显示;我可以稍后添加测试以匹配状态.true 将替换为实际测试.现在我只想要 active 类集

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;
        }
    ]);
}])

原始 DOM 元素:

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

添加装饰器后,这是我在浏览器的 DOM 中看到的:

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>

太好了!我可以在 DOM 中看到添加的属性,但我的浏览器忽略了它.就好像它是在 Angular 扫描 DOM 以获取指令之后添加的.如果我将代码更改为:

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?

推荐答案

Amy 你不需要实现这个指令,因为 angular-ui 实​​际上已经有了,请查看 ui-sref-active

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

这篇关于使用装饰器添加 Angular 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆