1

目标:填充具有动态表标题(通过 GET 检索)的表。因此,用于填充表的值(通过另一个 GET 检索)具有可以连接两者的 header_id:

IE

headers = [{name:header1, id:1}, {name:header2, id2}]
list_entries = [{value:'pop', header_id:1},{value:'bop', header_id:3}]

我不能直接在 list_entries 上使用 ng-repeat 来填充表格,因为我必须尊重某些表格单元格将为空的事实(没有与标题匹配的值)。

我想访问 $scope.headings 以便我可以遍历它,然后使用逻辑来匹配它的值(比较 header_id)。

对其他人来说,这似乎是一个愚蠢的问题,但我真的已经尝试过寻找一个好的方法。我真的很感激在这方面被指出正确的方向。

<script>
    var list = angular.module('listApps', []);

    list.config(function($httpProvider) {
             ... set defaults ...
    });

    list.controller('ListCtrl', function ($scope, $http, $timeout){

        var table_headings = xxxxxx; //root + ending

        /* Pull Table Headings*/    
        $http.get(table_headings.toString()).success(function(data,status){
            $scope.headings = data.response.fields_names;
            $scope.status = status;
            console.log(data.response.fields_names);
        }).error(function(result,status){
            $scope.data = result.data || "Request failed";
            $scope.status = status;
        });

        // match table headings to the respective values in order to populate table correctly
        $scope.mapping = [];

        // At this point, not even focusing on the function; just need to access $scope.headings
        angular.forEach($scope.headings, function(value, key){
            this.push(key+':'+value);
        }, $scope.mapping);
    });
</script>
4

1 回答 1

1

您也可以这样做(想法是使用带有 ng-repeat 指令的字符串表示法来调用数据的属性,即:item['property'] 而不是 item.property):

结果 [图片链接] 在此处输入图像描述

如您所见,如果对象不存在该字段,则该字段为空白。

模板

<table class="table table-bordered">
<thead>
    <tr>
        <th data-ng-repeat="head in headings">{{head.title}}</th>
    </tr>
</thead>
<tbody>
    <tr data-ng-repeat="item in data">
        <td data-ng-repeat="head in headings">{{item.id}} {{item[head.id]}}</td>
    </tr>
</tbody>
</table>

控制器

function ListCtrl($scope, $http) {
    $http.get('api/headings.json').then(function(result) {
        $scope.headings = result.data;    
    });
    $http.get('api/data.json').then(function(result) {
        $scope.data = result.data;
    });
}

模板对应的数据字段

[
    {"id": "H1", "title": "Heading 1"},
    {"id": "H3", "title": "Heading 3"},
    {"id": "H5", "title": "Heading 5"}
] /* headings.json */

[
    {"id": "D1", "H2": "Data H2D1", "H3": "Data H3D1", "H4": "Data H4D1", "H5": "Data H5D1"},
    {"id": "D2", "H1": "Data H1D2", "H2": "Data H2D2", "H3": "Data H3D2", "H4": "Data H4D2"},
    {"id": "D3", "H1": "Data H1D3", "H2": "Data H2D3", "H3": "Data H3D3", "H4": "Data H4D3", "H5": "Data H5D3"},
    {"id": "D4", "H1": "Data H1D4", "H2": "Data H2D4", "H4": "Data H4D4", "H5": "Data H5D4"},
    {"id": "D5", "H1": "Data H1D5", "H2": "Data H2D5", "H3": "Data H3D5", "H4": "Data H4D5", "H5": "Data H5D5"}
] /* data.json with missing fields*/
于 2013-04-04T05:24:26.077 回答