Question

I have an array with classes set in the controller (has to be this way, it's read from page's meta-template). I'd also like to have a conditional classes applied to the same element. Is it possible?

Edit, more info: my html element has classes that originate from two sources - one is a set of classes created by the controller (they are provided by a service outside of my code, I can't have them hardcoded in the view). The other source is an output of a condition (for example: if "$scope.activeElement === name_of_this_element, add 'active' class).
In ng-class directive, I can't use an object notation for unspecified list of classes (the first source) and I have to use an object notation for conditional classes.

Edit: found a solution (see below).

Was it helpful?

Solution 2

I found a solution - I placed the "fixed" classes in a regular class attribute (converted that string to an array first) and conditional ones in ng-class object, like this:

<td ng-repeat="cell in row.cells" class="{{cell.cssClass}}" ng-class="{active: condition}">

OTHER TIPS

Another option is to write an ng-class in this way

<div ng-class="[item.class, item.errorClass, item.locked ? 'locked-item' : '']"></div>

The fact that you stored a array of classes' name is not relevant here.

HTML

<div ng-class="arrOfClasses[condition]"></div>

Angular

app.controller('myCtrl', function($scope) {
    $scope.arrOfClasses = ['class1', 'class2', 'class3'];

    $scope.condition = 1; // what ever number here
});

A good way, and also to avoid using {{}} inside class would be with just an expression:

<td ng-repeat="cell in row.cells" ng-class="(condition ? 'active ' : '') + cell.cssClass">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top