问题
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