1

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?

2
  • What's happening when you do .addClass? any error in console? Commented Sep 22, 2016 at 15:50
  • @PankajParkar, there's an empty Chrome console with the current code. If I use .addClass() as element.addClass() it says .addClass is not a function, I assume it occurs because there's no JQuery Commented Sep 22, 2016 at 15:52

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah it does work since I've switched to element.addClass('tab'). Thanks:)) 5mins to accept
Once you fix the above, you also don't need to wrap the element.
2

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>

1 Comment

replace: true has been deprecated.. would not encourage to use it.. Without replace: true it would obviously work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.