javascript Angular ng-class

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Angular ng-class相关的知识,希望对你有一定的参考价值。

// add a class to an element based on the data (similar to addClass / removeClass)

// supose we have .old, .modern, .new css classes
<li
  ng-class="{
    old: movie.year < 1995,
    modern: movie.year > 1995 && movie.year < 2000,
    new: move.year > 2000
  }"
  ng-repeat="movie in movies.favorites">
  <p>{{ movie.title }}</p>
  <p>Released in: {{ movie.year }}</p>
</li>

//ngClass using String syntax
<div ng-class="textType">something</div>
//ngClass using Array syntax (to apply multiple classes).
<div ng-class="[styleOne, styleTwo]">something</div>

//ngClass using Evaluated expression
//Syntax: { 'class_to_be_applied' : expression or variable to be evaluated }
//*you must use the {} curly brackets so that Angular knows to evaluate that expression.
//toggle a variable to true or false
<input type="checkbox" ng-model="awesome"/> Are You Awesome?
<input type="checkbox" ng-model="giant"/> Are You a Giant?
//add the class 'text-success' if the variable 'awesome' is true
<div ng-class="{ 'text-success': awesome, 'text-large': giant }"/>
//*When using classes with hyphens '-' (like text-success) make sure you put single quotes around the class. 

// used with ternary operator
<li
  ng-class="movie.year < 1995 ? 'old' : 'modern'"
  ng-repeat="movie in movies.favorites">
  ...
</li>
//another example
ng-class="$even ? 'even-row' : 'odd-row'">

// *if you need to use BEM naming conventions, you'll need to put your class names in '' to avoid javascript errors:
ng-class="'item__box--single'"

//In combination with ng-repeat: you can apply classes to the first, last, or a specific number in a list/repeat using special properties of ng-repeat like $first, $last, $even, $odd, and a few others. 
//add a class to the first item
<li ng-class="{ 'text-success': $first }" ng-repeat="..."><li>
//add a class to the last item
<li ng-class="{ 'text-danger': $last }" ng-repeat="..."></li>
//add different classes to even/odd items
<li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="..."></li>

// You can also use ngClass inside 'class='
//example with string syntax
<div class="item ng-class:type;">something</div>
//example with array syntax
<div class="item ng-class:[styleOne, styleTwo];">something</div>
//example with evaluated data
<div class="item ng-class:{ 'text-error': wrong };">something</div>

以上是关于javascript Angular ng-class的主要内容,如果未能解决你的问题,请参考以下文章

如何为现有的 Javascript 库创建 Angular 库包装器?

从javascript 调用angular的函数

另一个 javascript 库上的 Angular 2 templateURL 功能

从 Angular 组件动态加载外部 javascript 文件

将外部css和javascript文件导入Angular 4

JavaScript---Angular 和JQuery