linyuanxie
linyuanxie

Reputation: 787

Conditionally apply css with ng-repeat?

I have a data like this:

$scope.datas= [["inProgressCounter","31"],["approvedCounter","3"],["pendingCounter","35"],["rejectedCounter","0"]]

show them with ng-repeat:
<ul>
 <li ng-repeat="info in datas">{{info[0]}}{{info[1]}}</li>
</ul>

Now there are 2 requirement.

1, Each li has its own css style, such as, the first li always has biggest font-size, and last li always has smallest font-size.

2, I have to apply different css style to itself base on data. For example:

if {{info[1]}} ="aaa" it always has green color style, no matter it is placed in first or last or mid. So simply say: the #1 requires a fixed css style from fist li to last li, and #2 requires apply css depends on content of data, it always go with the li which contains the center data.

Upvotes: 1

Views: 6156

Answers (3)

Delta
Delta

Reputation: 851

You could use ngStyle for example in order to get your green color as a background.

ng-style="{backgroundColor: $scope.getBackgroundColor(info[2])}"

$scope.getBackgroundColor(value)
{
 if(value == 'aaa')
   return 'red';
 if(value == 'bbb')
   return 'blue';
 return 'white'
}

and the same thing can be done with font size using $index

Upvotes: 3

Dmitriy T
Dmitriy T

Reputation: 201

Use the $first, $last and $index properties of the iterator:

    <ul>
     <li ng-repeat="info in datas"
         ng-class="{ 'big-font': $first,
                     'average-font': $index == 2,
                     'small-font': $last,
                     'red-color': datas[$index][1] == '35' }">{{ info[0] }}{{ info[1] }}</li>
    </ul>

Here's a working JSFiddle example: http://jsfiddle.net/npnyL5e1/

If you don't want to define a condition for each data ('red-color': datas$index == '35') then you can define your CSS classes based on your data and apply that data as classes to the elements, ex:

<ul>
     <li ng-repeat="info in datas"
         ng-class="{ 'big-font': $index == 0,
                     'small-font': $last,
                     'red-color': datas[$index][1] == '35' }"
         class="data-{{ info[0] }}">{{ info[0] }}{{ info[1] }}</li>
</ul>

and in your CSS:

.data-inProgressCounter {
    color: red;
}

.data-approvedCounter {
    color: green;
}

Upvotes: 3

AdminAffe
AdminAffe

Reputation: 136

Try something like

<ul>
    <li data-ng-repeat="info in data" data-ng-class="{'someClass1': $first, 'someClass2': $last, 'someClass3': info[0] === 'aaa'}">
    {{info[0]}}{{info[1]}}
</li>

Upvotes: 0

Related Questions