NewToJS
NewToJS

Reputation: 2101

AngularJS: How to add a class with ng-repeat

In my markup I'm using ng-repeat to add text to each li element plus I want to add a class (in addition to the 'fa' class). So far I'm doing this:

<ul class='social-icons' ng-repeat="social in myCtrl.socialArr">
        <li><i class="fa" ng-class={{social.iconClass}}></i><label>{{social.label}}</label></li>
</ul>

..but it's not working

in my controller I have:

self.socialArr = [
    {
        label: 'Facebook',
        url: 'facebook.com/',
        iconClass: 'fa-facebook'
    },{
        label: 'Twitter',
        url: 'twitter.com/',
        iconClass: 'fa-twitter'
    }...

Upvotes: 1

Views: 2854

Answers (4)

ram1993
ram1993

Reputation: 971

Here you are passing {{expression}} which is evaluted to string. But ng-class expect expression [ng-class="expression"].

You can use any of the following:

  1. With ng-class directive.

    a. ng-class="expression"

    b. class="ng-class: expression;"

  2. With Interpolation [{{expression}}]

    class="{{expression}}"

Note: :: is for one time bindingdoc link

Upvotes: 1

George Kagan
George Kagan

Reputation: 6124

<i class="fa {{::social.iconClass}}">
This is the most performant way, since no watchers are created.

Upvotes: 0

Thalaivar
Thalaivar

Reputation: 23632

If you have no conditional logic, you can basically just use traditional class itself, which would improve performance as ng-class directive would un-neccessarly trigger the digest cycles when in your case its not needed at all.

<ul class='social-icons' ng-repeat="social in myCtrl.socialArr">
<li>
   <i class="fa" class={{social.iconClass}}></i>
      <label>{{social.label}}</label>
</li>
</ul>

Upvotes: 1

Eugene Beliaev
Eugene Beliaev

Reputation: 871

Try this

<ul class='social-icons'>
  <li ng-repeat="social in myCtrl.socialArr">
    <i class="fa" ng-class="social.iconClass"></i>
    <label>{{social.label}}</label>
  </li>
</ul>

Upvotes: 2

Related Questions