添加使用装饰角指令 [英] Adding Angular directive using decorator
问题描述
我用角与1.4.8角度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
属性添加到该元素。对于现在,我只想让他们所有的亮点;我可以为以后的匹配状态添加测试。在真正
将与实际测试所取代。现在我只想有效
类集
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元素:
The original DOM element:
<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中添加的属性,但我的浏览器忽略它。这几乎就像它的的之后的角扫描的DOM的指令得到补充。如果我改变code为:
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');
...然后正常工作。 我在做什么错了?
推荐答案
艾米,你不需要实现这个指令,因为事实上角UI已经拥有了它,请检查的 UI-SREF主动
Amy you do not need to implement this directive as angular-ui in fact already have it, please check ui-sref-active
这篇关于添加使用装饰角指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!