简体   繁体   中英

AngularJS: Change cell class in a dynamically generated table based on cell value

I have a dynamically generated table by the following code:

<tbody>
    <tr ng-repeat="row in tableType.data.rows track by $index">
        <td ng-repeat="col in row track by $index" class={{getUnitCountCellColor(col)}}>{{col}}</td>
    </tr>
</tbody>

The data over which the table is iterated looks like:

[["69123", 20, 20, 40, 0, 0, 0, 0, 20, 20, 20, 0, 20, 20, 0, 20],
 ["69121", 20, 20, 40, 0, 0, 0, 20, 20, 40, 20, 0, 20, 20, 0, 20],
 ["69124", 20, 20, 40, 0, 0, 0, 0, 0, 0, 20, 0, 20, 0, 0, 0],
 ["69221", 20, 20, 40, 20, 0, 20, 0, 0, 0, 20, 0, 20, 20, 20, 40]
]

As you can see the data is a nested array. Now I am trying to set the colour of each cell based on its value, by called the method getUnitCountCellColor() which is defined in the parent controller scope.

The method simply gets the value and returns the colour class based on the value as a string. (eg: danger, success)

Currently it is being called only 4 times with value 'undefined' .

I tried to implement this with ng-class as:

<td ng-repeat="col in row track by $index" ng-class="getUnitCountCellColor(col)">{{col}}</td>

But then the method is not called at all.

Please help me implement this functionality, either by pointing out the error in my current code or by a different better approach.

Thanking You,

Using ng-class should work.

<td ng-repeat="col in row track by $index" ng-class='getUnitCountCellColor(col)'>{{col}}</td>

Here's a demo where I color all the zeros red.

Update

So you table is in a directive, and the cell-color method is in the controller. You can pass the getUnitCountCellColor function into the directive.

<count-table table-type='tableType' 
get-unit-count-cell-color='getUnitCountCellColor(col)'>
</count-table>

The scope in your directive looks like this:

scope: {
  tableType:'=tableType',
  getUnitCountCellColor: '&'
}

And the directive template looks like this:

<td ng-repeat="col in row track by $index" 
ng-class="getUnitCountCellColor({col: col})">{{col}}
</td>

Updated Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM