3

I have an angularjs directive restricted to class. How can I add this by using addClass method in angularjs

directive

app.directive('number', function() {
return {
    restrict: 'C',
    link: function () {         

    }
};

});

code

 <div id="test"></div>

I know it is possible by using jQuery like the following.

$( "#test" ).addClass( "number" );

Please help me in doing it by using angularjs

6
  • you can do this same way you do in jquery. element.addClass('number'). all you got to do is find the element. you can use find() method. but it is limited to lookups by tag name. Commented Oct 21, 2013 at 7:18
  • here element means my div id ? Commented Oct 21, 2013 at 7:20
  • i already told you can only find element with element name. not id. here element is your div. Commented Oct 21, 2013 at 7:24
  • 2
    You cannot add directive class dynamically onto the html. html has to be compiled before any directive can work on it. Since you want to add it dynamically it would not work? Why do you want to do like this. Please explain your scenario. Commented Oct 21, 2013 at 7:24
  • I have to give this class to one of the value which comes through a ng-repeat Commented Oct 21, 2013 at 8:27

3 Answers 3

8

You don't need to use .addClass() angular provide ng-class directive to add class conditionally.

ng-class="{number:[condition]}"

it will add class number whenever your condition return true

yes but your directive will not be used by this I misunderstood your question previously.

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

Comments

4

You should add ng-class="yourClass" to element on view and add in your controller

$scope.yourClass = "your-new-class", not in directive

Comments

1

try this

 link: function (lEmel) {         
      lElem.addClass("Foo");
    }

Comments

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.