It turns out that property name in the single quotes will directly be added to the class when value is true.
ng-class="{'first second third': isTrue}"
works.
Question
I want to bind one more class to a value, like this:
ng-class="{first: isTrue, second: isTrue, third: isTrue}"
Is ng-class
Exists any usage can bind them in once, like this? (below code is not working)
ng-class="{[first, second, third]: isTrue}"
Solution
It turns out that property name in the single quotes will directly be added to the class when value is true.
ng-class="{'first second third': isTrue}"
works.
OTHER TIPS
What you need to know about the ng-class
directive is that the value you pass in is actually evaluated roughly as if it were actually JavaScript. (It actually uses $scope.$eval
, I believe.) What that means is that you can call a function that is available on the $scope
to generate your class hash object. I quite like the solution you came up with, taking the classes you need and spacing them out, but what if you had a dynamic list of classes that you wanted to apply to the element? Because the syntax is roughly JavaScript, you can't build an object by doing {list.join(' '): isTrue}
(since that wouldn't be valid in JavaScript). However, what you can do is write a function and add it to the scope which does that:
angular.module('app')
.controller('MyCtrl', function($scope) {
$scope.myList = ['first', 'second', 'third'];
$scope.allOrNoneClasses = function(list, condition) {
var o = {};
if (condition) {
o[list.join(' ')] = true;
}
return o;
};
$scope.scopeBasedClasses = function(list) {
var o = {};
list.forEach(function(class){
// this applies a class which matches the scope attribute if
// the attribute evaluates to a truthy value.
o[class] = $scope.$eval(class);
});
return o;
};
});
This could then be used in your HTML as follows:
<div ng-class="allOrNoneClasses(myList, isTrue)" />