Search code examples
angularjsangularjs-ng-repeatcellangular-ui-grid

ui-grid : directive as cellTemplate


I'm using ui-grid with the following data structure :

{
 name: String,
 tags: [{label: String, image: String}] 
}

So the grid would have 2 columns : name and tags. A row entry can have multiple tags associated to it (hence the Array). Each tag has two properties : a label and an image, which is the path for an image file.

I've created a directive that displays tags (directiveTags for example):

For the sake of simplicity :

<div>{{tag.label}}<img ng-src={{tag.image}}></div>

How would one use this directive in the cellTemplate property of gridOptions ? My idea was something like :

columnDefs: [
            { field: 'name'},
            { field: 'tags',
              cellTemplate : "<div ng-repeat="tag in tags"><directive-tags></directive-tags></div>"
            },

Help much appreciated.


Solution

  • Checking the documentation for custom row templates we can see that the row object is accessible from row templates, for example: grid.appScope.fnOne(row). Following the example and trying to run this, the row object is logged to console. row contains the entity key and this is where the row data is stored.

    You are very close with your example, you just need to replace tag in tags with tag in row.entity.tags and rename your directive to not contain a dash (since I haven't worked with directives before and being on my first cup of coffee, I also got stuck at this for a while, dashes in directive names does not parse).

    Here is a plunker: http://plnkr.co/edit/P1o1GolyZ5wrKCoXLLnn?p=preview

    var testApp = angular.module('testApp', ['ui.grid']);
    
    testApp.directive('directivetags', function() {
      return {
            restrict: 'E',
            template: '<div>{{tag.label}}<img ng-src={{tag.image}}></div>',
            replace: true
        }
    });
    
    testApp.controller('TestCtrl', function($scope) {
    
      $scope.grid = {
        rowHeight: 50,
        data: [{
          name: 'Test',
          tags: [{
            label: 'Suwako Moriya',
            image: 'http://i.imgur.com/945LPEw.png'
          }]
        }],
        columnDefs: [
              { field: 'name'},
              { field: 'tags',
                cellTemplate: '<div style="height: 50px" ng-repeat="tag in row.entity.tags"><directivetags></directivetags></div>'
              }
        ]};
    });