2014-02-27 85 views
2

我正在編寫一個指令,表示一個表中填充動態數據的表。動態數據包括列的動態數量以及..Angularjs - 動態數據指令 - 從字符串創建對象

這裏是我的plunkerhttp://plnkr.co/edit/pmCjQL39BWWowIAgj9hP?p=preview

我的指令代碼如下所示:

app.directive("myTable", function() { 
    return { 
    restrict: "E", 
    replace: true, 
    scope: true, 
    controller: function($scope, $element, $attrs, $http) { 

    // Get Table Data 
    $http.get('my-table.json').success(function(data) { 
    $scope.tableData = data; 
    console.log($scope.tableData); 

    $scope.tblKeys = []; 

    for (key in $scope.tableHeader) { 
     if ($scope.tableHeader.hasOwnProperty(key)) { 
     $scope.tblKeys.push({key: key}); 
     } 
    } 
    console.log($scope.tblKeys); 

    }); 
    }, 
    templateUrl: "template.html", 
    compile: function(element, attrs) { 

    return function(scope, element, attrs) { 

    scope.css = attrs.css; 
    attrdata = attrs.values; 

    //attrdata = "{'id':'ID Col', 'name':'Name Col', 'price':'Price Col', 'qty':'Quantity'}"; 

    convertdata = attrdata.replace(/'/g, '"'); 
    json = JSON.parse(convertdata); 

    scope.tableHeader = json; 
    console.log(scope.tableHeader); 

    }; // return 

    } // compile 
    } 
}); 

這是指導模板

<table class="{{css}}" width="80%"> 

<thead> 
<tr> 
    <th ng-repeat="title in tableHeader"> 
     {{title}} 
    </th> 
    <th> 
     Cost 
    </th> 
</tr> 
</thead> 

<tr ng-repeat="items in tableData"> 

    // >>>>>>>> THIS IS WHERE I NEED HELP <<<<<<<< 

    <td> {{ items.id }}</td> 
    <td> {{ items.name }}</td> 
    <td> {{ items.price }}</td> 
    <td> {{ items.qty }}</td> 

    <td> {{ items.qty*items.price }}</td> 

</tr> 
<tr> 
    <td></td> 
    <td></td> 
    <td></td> 
    <td colspan="2">Total</td> 
</tr> 

</table> 

的問題


我的指令被認爲是能夠動態地設置列中的數據。我已經能夠從指令接收的表格對象中獲取值的鍵值作爲參數,但我無法使用存儲在scope.tblKeys中的動態鍵值從tabeData對象動態填充表格數據。

在我的模板這4條線,我想避免使用ID,名稱,價格,數量和scope.tblKeys

<td> {{ items.id }}</td> 
    <td> {{ items.name }}</td> 
    <td> {{ items.price }}</td> 
    <td> {{ items.qty }}</td> 

的東西,而不是獲得這些數據以某種方式的

<tr ng-repeat="items in tableData"> 

    <td ng-repeat="key in tblKeys"> {{ items.key }}</td> 

    <td> {{ items.qty*items.price }}</td> 
</tr> 

調我不知道如何做到這一點{{ items.key }},我寫這部分說明什麼,我需要

<td ng-repeat="key in tblKeys"> {{ items.key }}</td> 

我想我可以用角$解析,但我不知道如何處理這一點。

我真的很感謝一些幫助。

回答

2

問題是,你正在存儲爲key有這樣的結構:{"key":"id"},所以當你做{{ items.key }},這個項目對象沒有任何屬性被稱爲鍵。

如果您打算顯示items.id的值,您想要{{ items[key.key] }}

updated plunker

編輯:或者你很可能逃脫推只有字符串到scope.tblKeys

$scope.tblKeys.push(key); 

而且隨着訪問它在你的指令:

{{ items[key] }} 
+0

謝謝!! !我有一個漫長的一天,我以爲我瘋了!解決:) – GRowing

+0

沒問題。這是一個非常酷的想法。幾年前,我必須使用C#和Linq-to-sql在服務器端創建動態生成的表。這是比你擁有的更多的代碼。;) –

+0

事實上,我將把你的實現與我在那個項目上工作的人聯繫起來。謝謝。 –