-1

I am using ngGrid and in the process of customizing a cell template, I came across a situation where I would like to use ngClass to create a dynamic class name as well as optionally add another class onto a single element.

I know that ngClass can be used in multiple ways. The two I am interested in combining are as follows

<input type="text" data-ng-class="'colt' + col.index"/>

<input type="text" data-ng-class="{'error' : cptForm.$invalid}"/>

Is there anyway to combine these usages of ngClass? Something like

<input type="text" data-ng-class="{'colt' + col.index: true, 'error' : cptForm.$invalid}"/>

Alternatively, I could create a method on my controller that does the work of creating both of these classes, but I would like to do the work in-line if I could.

jstromwick
  • 1,206
  • 13
  • 22
  • wouldn't make more sense to have a function called `getCSSClass(index, isInvalid);` based on MVVM approach it will be more appropiate. – Dalorzo Aug 06 '14 at 17:20
  • 1
    @Dalorzo that is one way to do it, but it feels like a leaky abstraction to have the controller creating CSS class names. It would be nice to be able to have that logic stay in the view. – jstromwick Aug 06 '14 at 17:41
  • I used that name to simplify but it is clearly that the CSS obeys a more abstract rule one the rule has a name it will simpler to 'CCSify' once it does have a name... my POV at least – Dalorzo Aug 06 '14 at 17:47

2 Answers2

1

I'm not entirely sure what you're are trying to do but you can use the data binding within the standard class attribute, like ...

<div class="normal-class colt{{ col.index }}" 
     ng-class="{ 'error': cptForm.$invalid }"></div>

Also not sure what the data- prefix for mg-class.

dev
  • 3,969
  • 3
  • 24
  • 36
  • The `data-` prefix is just decorative. Adding `data-` to custom attributes (those not defined in the HTML 5 Scheme) makes them valid HTML: http://stackoverflow.com/questions/16184428/what-is-the-difference-between-ng-app-and-data-ng-app – jstromwick Aug 06 '14 at 18:59
  • Thanks, handy to know. – dev Aug 06 '14 at 19:05
  • Cool. This totally works, but I ended up using an array for `ngClass`. This allowed me to get both classes on the element using a single attribute. – jstromwick Aug 06 '14 at 21:58
0

Apparently a third way to use ngClass is as an array of classes. This array can contain arbitrary javascript and is interpreted by angular. This is what I ended up going with:

<input type="text" data-ng-class="['colt' + col.index, cptForm.$invalid ? 'validation-error' :'' ]"/>

Someone else posted this as an answer and then deleted their answer, but it works great!

jstromwick
  • 1,206
  • 13
  • 22