Search code examples
javascriptangularjsng-grid

In angular ng-grid how to specify a count for a sub array


I need to specify a count of x units if a field contains an array of more than one items. How do I do this in ng-grid field display names?

Json Example: $scope.data = [{id: {1, 3}, nm: John Doe} , {id: {2,4,5}, nm: Jane Doe}]

Current result:

Id              Name
--------------  -------------------------------
1,3             John Doe
2,4,5           Jane Doe

Desired result:

Id              Name
--------------  -------------------------------
2 Ids           John Doe
3 Ids           Jane Doe

Current Angular code:

                $scope.gridOptions = {
                    data: 'data',
                    selectedItems: $scope.mySelections,
                    columnDefs: [
                    {field: 'id', displayName: 'Id', width: '***'},
                    {field: 'nm', displayName: 'Name', width: '****'}],
                    multiSelect: false
                };

Solution

  • Just create a cell template like this:

    <div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{row.getProperty("id").length}} Ids</span></div>
    

    Then apply it like so:

    var app = angular.module('myApp', ['ngGrid']);
    app.controller('MyCtrl', function($scope) {
    
    
        $scope.myData = [{id: [1, 12], name: 'John Doe'},
                         {id: [3, 7, 9, 6, 2], name: 'John Doe'},
                         {id: [10, 52, 78], name: 'John Doe'},
                         {id: [101, 88, 72, 99], name: 'John Doe'}];
    
    
        $scope.columnDefs = [
          {
            displayName:'Id',
            cellTemplate: 'cellTemplate.html'
          },
          {
            field:'name', displayName:'Name'
          }
        ]
    
        $scope.gridOptions = { 
          data: 'myData',
          columnDefs: $scope.columnDefs 
        };
    });
    

    Example: Plunker