Basic Angular Template

by marco_m_alves

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div ng-controller="ctrl">
    <xy-table source="data"></xy-table>
</div>

JavaScript

var app = angular.module('app', []);

function ctrl($scope) {
    $scope.x = 3;
    $scope.y = 3;
    $scope.data = [
         {"x":"1","y":"1","name":"will"},
        {"x":"3","y":"1","name":"dave"},
         {"x":"2","y":"1","name":"joe"},
          {"x":"1","y":"2","name":"steve"}
          ];
}

app.directive('xyTable', function(){
    return {
        restrict: 'E',
        scope: { source: '='},
        template: '<table class="table table-bordered"><tr ng-repeat="row in rows"><td ng-repeat="col in cols[row]">{{col.name}}</td></tr></table>',
        controller: function($scope){
            $scope.$watch('data', function(){
                $scope.rows = _.unique(_.pluck($scope.source, 'y'));
                
                $scope.cols = {};
                
                $scope.rows.forEach(function(row){
                    $scope.cols[row] = _.sortBy(_.filter($scope.source, function(item){ return item.y == row;}), 'x');
                });
                
            });
        }
    };
});