Kishore L Kishore L - 4 months ago 8
AngularJS Question

Apply color on the item using custom filters in AngularJs

I have an array of objects:

[
{
idPriority: 1,
priority: "Critical",
isChecked: 0
},
{
idPriority: 2,
priority: "High",
isChecked: 0
},
{
idPriority: 3,
priority: "Medium",
isChecked: 0
},
{
idPriority: 4,
priority: "Low",
isChecked: 0
}
]


I want to display this data inside a table using ng-repeat and apply a custom filter such that if the priority of the object is High or critical, it should be displayed in red color and if the priority is medium or low, it should be displayed in yellow color. Is it even possible?

NTP NTP
Answer

You can create different columns with different styles and change their visibility according to the value of priority

<tr ng-repeat=" item in items">
    <td>
        <span class="style for red" ng-show="item.priority=='Critical'">Critical</span>
        <span class="style for yellow" ng-show="item.priority=='High'">High</span>
        <span class="style for green" ng-show="item.priority=='Medium'">Medium</span>
    </td>
</tr>

or if you want a custom filter, you can create a filter and set its class in it

    $scope.filterPriority = function (item) {
    if (item.priorty == 'High') {
        item.class = 'class for high';
    }
    else if (item.priorty == 'Low') {
        item.class = 'class for low';
    }
    else {
        item.class = 'default class';
    }

    return true;
};

and in your html

<table>
<tr ng-repeat=" item in items | filter:filterPriority">
<td>
    <span class="{{item.class}}"></span>
</td>                           
</tr>