Lukas Chen Lukas Chen - 4 months ago 28
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

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>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body>
  <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>
</body>

</html>