1

I can't get this to work.

<div ng-repeat="title in titles">
   <h1>{{title.name}}}</h1>
</div>

What I want to do, is to get the length of the title. So let's say if the title has 10 letters, I want to give it a specific class.

I tried this:

<h1 ng-class="title.name.length >= 10 ? 'specific-class'">{{title.name}}}</h1>

(found it here, by the way: angular ng-class if-else expression).

But it didn't work, so clearly I am doing something wrong.

halfer
  • 19,824
  • 17
  • 99
  • 186
Siyah
  • 2,852
  • 5
  • 37
  • 63

2 Answers2

2

In this case, you don't need ternary operator. It could be the following:

<h1 ng-class="{'specific-class': title.name.length >= 10}">{{title.name}}</h1>

JSFiddle demo

Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • Thanks man. The thing is... it doesn't add the class to my classname. What am I doing wrong? No it just has class="ng-binding", but the new class isn't being added... – Siyah Jan 20 '17 at 10:45
  • @Siyah I don't understand what your issue is. Could you provide your real code by forking my Fiddle? – Mistalis Jan 20 '17 at 10:46
  • @Siyah Glad I helped! :-) – Mistalis Jan 20 '17 at 10:47
1

You can use the terniary-operator which best suits for these kind of situations.

You can add class based on both the true or false result of the condition.

Try this,

<h1 ng-class="((title.name.length) >= 10) ? 'specific-class' : 'other-class'">{{title.name}}}</h1>

This once adds specific-class if condition satisfies and other-class if it fails

Here is an example,

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>

.specific-class {
    background-color:coral;
    padding:40px;
    font-family:Verdana;
}
</style>
<body ng-app="">

<div ng-class="(15 >= 10) ? 'specific-class' : ''">
  <h1>Welcome Home!</h1>
  <p>I like it!</p>
</div>

</body>
</html>

Please run the above snippet

Sravan
  • 18,467
  • 3
  • 30
  • 54