2

Several times when creating or customizing a directive (either my own directive or for example https://github.com/dpiccone/ng-pageslide) I get a point where all the display logic is controlled by a single css class. At that point the directive boils down to adding and removing a single class. So instead of using a new directive I can simply use the ng-class directive (see an example here: https://gist.github.com/Hypercubed/8f40556eb0f6eddbcca3). Is there an advantage to the custom directive approach vs the ng-class/CSS styles approach? I guess the custom directive doesn't depend on $animate? Am I just doing it wrong?

Sorry for another directive vs. XXX question.

3
  • Directives are existing in order to add behaviour, not to style. If one of your directive ends up by just add style, then you should use the ngClass directive directly, especially if the style is controlled by a simple boolean variable. There is no point in creating a directive which just add or remove classes… since this is exactly the goal of ngClass! Commented Jul 15, 2014 at 1:45
  • Thanks for your reply. It maybe just semantics but If something (like a sliding panel) is activated/deactivated by a class tag is it a style or behavior? Commented Jul 15, 2014 at 2:03
  • To toggle between a hidden and a shown status is a behaviour, I think. A really common one, actually, that's why there is already a directive for that in the core of AngularJS ;) . Commented Jul 15, 2014 at 2:10

1 Answer 1

2

I think you're failing to see the forest for the all tress. You're focusing on a very minute detail and missing the larger picture. Directives are more than simply applying styles. I think an example is best. For example, take the rating directive. If you wanted to render a star rating model it might look like this:

<div ng-rating="album.rating" max="5"></div>

That may add the following to the DOM:

<ul class="inline">
    <li ng-repeat="i in max">
        <i ng-class="{ 'icon-start-empty': i > rating, 'icon-star': i <= rating }"></i>
    </li>
</ul>

Under the covers ng-class it utilized, but that is only a part of the logic encapsulated in the rating directive. It allows the user to configure how many stars the rating is out of, and renders the same number of li elements. Then because you wrote a directive it allows you to reuse this logic where ever it's required. Using ng-class only works in that 1 location. If you want to do the same thing you're copying code which is a sign maybe you want to wrap that logic up in a directive.

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

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.