简体   繁体   中英

what is better angular directive or css selector?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM