Reputation: 2367
Have tab
css class for the nav
html element which I'm going to use as directive like this:
<nav tab></nav>
It expected to be interpreted like this:
<nav class="tab">
<a></a>
<a></a>
<a></a>
</nav>
... and everything works almost as expected except of the issue I cannot set the CSS class to the top <nav>
element. Of course, I could specify it using ng-class
explicitly but it seems to be not a great idea.
Have heard about .addClass()
option but it doesn't work at all:
tab.directive('tab', function($compile) {
return {
restrict: 'A',
templateUrl: 'nav-tab.html',
controller: function($http, $scope) {
$http.get('/Tab/List')
.success(function(data) {
$scope.tabs = data;
}).error(function() {
alert("error");
});
},
controllerAs: 'tab',
link: function(element, scope) {
angular.element(element).addClass('tab');
$compile(element)(scope);
}
}
});
How to add the CSS class to the top directive element without it's explicit specifying right at the element?
Upvotes: 1
Views: 1402
Reputation: 1136
I would change your directive to be an "element" ('E' instead of 'A' for attribute)
<tab></tab>
tab.directive('tab', function($compile) {
return {
restrict: 'E',
templateUrl: 'nav-tab.html'...
and then add the class in your template nav-tab.html:
<nav class="tab">
<a></a>
<a></a>
<a></a>
</nav>
Upvotes: 2
Reputation: 136134
You have a wrong sequence in link function
Instead of
link: function(element, scope) {
Change it to
link: function(scope, element, attrs) {
Then you can directly do element.addClass
as jQLite
api has .addClass
method available on it.
Upvotes: 3