WildDev WildDev - 2 months ago 14
AngularJS Question

AngularJS - how to set css class for the custom directive?

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?

Answer

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.

Comments