1

I'm learning angular and I'm testing the directive ngClass. With ngClass I can do something like that:

<li ng-repeat="language in languages" ng-class="{line:$even}">{{language}}</li>

But I can also do this with the css selectors:

li:nth-child(even) {
   // some css code here
}

What is better?

3
  • What is "this" that you're doing that can somehow be done using either approach? Commented Feb 9, 2015 at 12:06
  • you need javascript enabled to show ng-class="{line:$even}. The css approach does not need javascript; thats the difference. Commented Feb 9, 2015 at 12:09
  • Better? In what way? Better is a very broad term and will most likely depend on what you're trying to do as a whole, what your project is based on, etc... Commented Feb 9, 2015 at 12:12

2 Answers 2

2

First of all two cases are not equivalent. But if what you are looking is a way to style even/odd elements, then without any doubt: you should use CSS to do CSS job, not javascript. Using javascript to add class names is possible but if it's not important to have actual class names on elements then sticking to :nth-child approach is preferred in this case.

Two main benefits of pure CSS way:

  • Avoiding additional watchers Angular would have to set for data binding.
  • Performance and cleaner HTML code.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, i was looking for a answer like.
1

I see ng-class as a visual port of some property of the model. It is not intended just for styling, but can offer it.
IMO it is always best to do as much as you can using standards, that way you're less dependent on others.
There are plenty other reasons why using CSS is better, like: performance, less error prone, less dependent etc.

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.