Angular JS:用json创建表

时间:2014-03-08 18:12:27

标签: javascript jquery json angularjs

我在angular-JS中创建了一个应用程序,用于创建包含json

动态列的表

例如,从服务返回的JSON结构位于主JSON的其他字段包含另一个JSON数组的结构中,该数组是附加列,

所以总共将有四个额外的动态列,即文件1,文件2,文件3,文件4 每个对象具有相应文件字段的值,有时某些时候不存在。

$scope.getColumns = function()
{
    //console.log( $scope.datas[0].others[0]);
  $scope.datas.resultsOrder = new Array();
     for ( var i = 0; i < $scope.datas.length; i++)
     {
       for ( var j = 0; j < $scope.datas[i].others.length; j++)
        {
        if (countInstances($scope.datas.resultsOrder, $scope.datas[i].others[j].id) < countInstances(
                    $scope.datas[i].others, $scope.datas[i].others[j].id)){
           $scope.datas.resultsOrder.push($scope.datas[i].others[j].id);
         }
        }
      }        
$scope.datas.resultsOrder.sort(function(a, b){
    return a.localeCompare(b);
  });
return $scope.datas.resultsOrder;
}

我已经使用javascript帮助完美地显示了动态列的表格,但是任何人都可以告诉我通过角度js以简单的方式创建上述动态表的其他方式,因为在我的代码中我使用了javascript用于创建动态列的复杂逻辑,如下所示

我的JS-Fiddle如下:

Demo

1 个答案:

答案 0 :(得分:3)

这将创建一个名为columns的对象,其中属性是动态列的名称('File 1','File 2'等)

控制器:

$scope.columns = {};

angular.forEach( $scope.datas, function(data){

    angular.forEach( data.others, function(other){

        // Set the 'File x' property for each item in the others array
        data[other.id] = other.value;

        // Add the dyanmic column to the columns object
        $scope.columns[other.id] = null;
    });
});

查看:

<!-- table header -->
<tr>
    <th ng-repeat="(column,val) in columns">
        <a ng-click="sort_by()"><i>{{column}}</i></a>
    </th>
....
</tr>

<!-- data rows -->
<td ng-repeat="(column,v) in columns">{{val[column]}}</td>

Fiddle