Lukas Chen Lukas Chen - 1 year ago 88
AngularJS Question

How to have string syntax and evaluated syntax in ng-class

I am looking for something like this:

<input type="text" ng-model="stuff1">

<input type="checkbox" ng-model="stuff">

<div ng-class="{'stuff': stuff};stuff1">Stuff!!!</div>

However this doesn't work

Answer Source

You can achieve what you want by two ways:

  1. Using the array notation of ngClass:
<div ng-class="[{'stuff': stuff}, stuff1]">Test</div>
  1. Separating class and ngClassdirective, as below:
<div class="{{stuff1}}" ng-class="{'stuff': stuff}">Stuff!!!</div>

Take a look:

<!DOCTYPE html>
<html ng-app>

  <script src=""></script>
  <link rel="stylesheet" href="" />

  <input type="text" ng-model="stuff1">
  <input type="checkbox" ng-model="stuff">
  <div ng-class="[{'text-success': stuff}, stuff1]">Stuff1!!!</div>
  <div class="{{stuff1}}" ng-class="{'text-danger': stuff}">Stuff2!!!</div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download