Search code examples
angularjsng-gridng-class

Angularjs ng-class with ng-grid / swapping css style


I have this very simple angular app using ng-grid. I for some reason don't know how to apply style based on data. I need to be able to display different status image based on data status Code below:

controller:

$scope.myData2 = [
            {service: "aaa", status: "ok"},
            {service: "ccc", status: "warning"}];
$scope.gridOptions2 = {
            data: 'myData2',
            headerRowHeight:0,
            rowHeight: 39,
            enableRowSelection: false,
            enableHighlighting:true,
            columnDefs: [
                {field: 'service', enableCellEdit: true},
                {field:'status', cellTemplate : 'stateTemplate.html'}]
        };

directive:

angular.module('myApp')
    .directive("statusIcon", function() {
        return {
            restrict: 'E',
            template: "<div ng-class=status-{{row.getProperty('status')}}></div>"
        };
    });

template:

<status-icon></status-icon>

css:

.status-ok{
    width: 24px;
    height: 24px;
    background: url("../images/status_ok.png") no-repeat;

}

.status-warning{
    width: 24px;
    height: 24px;
    background: url("../images/status_ok.png") no-repeat;

}

when I render the page this is the output:

<status-icon class="ng-scope"><div ng-class="status-ok"></div></status-icon>

I'm missing a classic class="status-ok"

What am I doing wrong?

PLUNKR http://plnkr.co/edit/4xTC4pKIR0AnzD89iIp2?p=preview


Solution

  • have a look at cell templating article here.

    columnDefs: [{ field: 'firstName', displayName: 'First Name', width: 90, cellTemplate: '<div>{{row.entity[col.field]}}</div>' },
                         { field: 'lastName', displayName: 'Last Name', width: 80 },
                         { field: 'age', cellClass: 'ageCell', headerClass: 'ageHeader' } ]
    

    you can define cellClass or headerClass or completely different cellTemplate

    EDIT

    below is example on how to use ng-class with cell template

    <div ng-class="row.entity[col.field] == 'success' ? 'successClass' : 'errorClass'">{{row.entity[col.field]}}</div>
    

    EDIT

    working plunker

    you dont need ng-class you just need class