简体   繁体   English

什么是更好的角度指令或CSS选择器?

[英]what is better angular directive or css selector?

I'm learning angular and I'm testing the directive ngClass. 我正在学习角度,我正在测试指令ngClass。 With ngClass I can do something like that: 使用ngClass我可以做类似的事情:

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

But I can also do this with the css selectors: 但我也可以用css选择器做到这一点:

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. 但是,如果您正在寻找一种方式来设计偶数/奇数元素,那么毫无疑问:您应该使用CSS来完成CSS工作,而不是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. 使用javascript添加类名是可能的,但如果在元素上有实际的类名并不重要,那么坚持:nth-child在这种情况下,首选:nth-child方法。

Two main benefits of pure CSS way: 纯CSS方式的两个主要好处:

  • Avoiding additional watchers Angular would have to set for data binding. 避免其他观察者Angular必须设置数据绑定。
  • Performance and cleaner HTML code. 性能和更清晰的HTML代码。

I see ng-class as a visual port of some property of the model. 我认为ng-class是模型某些属性的可视化端口。 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. IMO总是最好尽可能多地使用标准,这样你就不那么依赖别人了。
There are plenty other reasons why using CSS is better, like: performance, less error prone, less dependent etc. 使用CSS的原因还有很多,比如:性能,更少出错,更少依赖等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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