I have a very simple Angular App and I'm trying to use ng-repeat in conjunction with ng-class to repeat a template and apply a different class to the outer div depending on one of the properties of the data being bound.
this worked when I used a simple...
ng-class="message.type"
...but unfortunately I need to concatenate a string to the start of the message type.
I tried to create a JSfiddle here...
http://jsfiddle.net/XuYGN/5/
... but it's my first attempt at making a JSfiddle too and I must be doing something wrong because the Angular stuff doesn't seem to be running. It does show what I'm trying to do with the expression though.
Any help would really be appreciated.
yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.
AngularJS ng-class Directive The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names.
ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.
Ultimately, NgClass can take the following as input: A space-delimited String [ngClass]="is-info is-item has-border" An Array of Strings [ngClass]="['is-info', 'is-item', 'has-border'"] An Object [ngClass]="{'is-info': true, 'is-item': true}
html :
<div ng-controller="mainCtrl">
<div ng-repeat="message in data.messages" ng-class="'className-' + message.type">
Repeat Me
</div>
</div>
</div>
javascript :
var mainCtrl=function($scope) {
$scope.data = {}
$scope.data.messages = [
{
"type": "phone"},
{
"type": "email"},
{
"type": "meeting"},
{
"type": "note"}
]
}
in the fiddle you put some {{}} around the expression dont do it because it is an expression.
FYI, an alternative to what @camus answered:
class="{{'className-' + message.type}}"
When using class
, the expression (inside {{}}s) must evaluate to a string of space-delimited class names.
When using ng-class
, the expression must evaluate to one of the following:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With