简体   繁体   中英

How to change and manipulate the data inside a cell ng-grid with AngularJS?

I am using ng-grid from AngularJS:

var app = angular.module('myApp', ['ngGrid']);
    app.controller('MyCtrl', function($scope) {
        $scope.myData = gridData;
        $scope.gridOptions = {
                        data: 'myData',
                        columnDefs: ColumnArray
                        };
    });

I want to change a cell text inside a cell. How to do that? I was using cellTemplate:

ColumnObject.cellTemplate = GetCellTemplate();

But, my GetCellTemplate method can not read {{ row.getProperty(col.field) }} which is the data in the current cell. What to do in order to be able to read the cell data/text and change it in run time.

For example, if my cell has text like "My Name IMAGE" I want to be able to change the word "IMAGE" into a real image and display it in my ng-grid.

How can I do that?

You can use an angular directive in the cellTemplate.

For example:

.directive('replacewithimage', function(){
            return {
                restrict: 'C',
                replace: true,
                transclude: true,
                scope: { colValue:'@colValue' },
                 template: '<div ng-switch="colValue">' +
                    '<div ng-switch-when="IMAGE"><img src="#"></div> '     +
                    '<div ng-switch-default>{{valor}}</div> '
                    +'</div>'
            }


    })

and then use it in the cellTemplate of the ng-grid passing the "class" name as "replacewithimage" and the value as the "colValue" attribute

> ..
  cellTemplate: '<div> class="replacewithimage"
> colValue="{{row.getProperty(col.field)}}"></div>'},
..

@l2mt, I tried your example with following changes:

template: '<div ng-switch="colValue">' +
            ' <div ng-switch-when="1">Valid Data</div>' +
            '<div ng-switch-when="2">Invalid Data</div>' +
            '<div ng-switch-default>NONE</div>' +
          '</div>

There are 2 row in a ng-grid column with values 1 and 2.

cellTemplate has the same code as yours. But it displays NONE for both the rows not "Valid Data" or "Invalid Data".

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