RussK
RussK

Reputation: 33

Setting class values in Angular template

I'm a bit of an Angular novice an I'm struggling with something I thought would be very simple.

I have a template that is used in a read only version of a form in my app. This template displays a status field that would be styled (text/background colour) based on its value, e.g

'New issue' - orange 'In progress' - green 'Overdue' - red

etc...

My css is something like;

.status-bar {padding: 3px; border: solid 1px #333}
.new-issue {background-color: orange; color: #000}
.in-progress {background-color: green; color: #fff}
.overdue {background-color: red; color: #fff}

The issue status field is available through the controller and i use code something like this to display it.

<div class="status-bar">{{issue.status}}</div>

All works fine.

I then naively tried to simply insert the class name as an expression, e.g

<div class="status-bar {{issue.status}}">{{issue.status}}</div>

Thinking that would give me a this kind of output..

<div class="status-bar overdue">overdue</div>

But it doesn't work. I've looked at the ng-class directive, and other options but can't work this out.

Ideally I need a solution that would allow me to append/insert a class name based on a value (not a true/false like ng-class). So I'd like my oputput HTML to be like the following...

<div class="status-bar in-progress">In Progress</div>

OR

<div class="status-bar new-issue">New Issue</div>

OR

<div class="status-bar overdue">overdue</div>

etc...

The range of status values may change so my class names must be calculated as per the above pattern

e.g,

<div class="status-bar another-status">Another Status</div>

So I need a way to hyphenate and lowercase my issue.status value and then add it as a class name. I presume a directive is the way forward, which would be ideal so I can use it in other views.

This is so easy to do after the fact in jQuery etc..., but I can't see the 'Angular' way to do it?!

Many thanks upfront for any help provided...

Upvotes: 3

Views: 1271

Answers (3)

Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

ng-class with a custom filter is what you are looking for...

HTML

<h1 ng-class="class1">{{class1 | titleCase}}</h1>

JS

app.filter('titleCase', function () {
  return function (input) {
    var words = input.split('-');
    for (var i = 0; i < words.length; i++) {
      words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
    }
    return words.join(' ');
  }
});

and here is working PLUNKER...

Upvotes: 1

Jscti
Jscti

Reputation: 14450

ng-class should work :

<div class="status-bar" ng-class="issue.status">{{issue.status}}</div>

Working fiddle : http://jsfiddle.net/w2SFr/2/

Upvotes: 1

michas84
michas84

Reputation: 177

What You are looking for is probably http://docs.angularjs.org/api/ng/directive/ngClass. You may also want to look at AngularJS ngClass conditional

Upvotes: 0

Related Questions