2017-09-02 156 views
2

內的JSON的值,讓我們說我有這樣JSON:使用NG-重複AngularJS

var myObj = { 
    {"key1":"value1", "key2":5, "key3":"value3" }, 
    {"key1":"value4", "key2":2, "key3":"value5" }, 
    {"key1":"value6", "key2":4, "key3":"value6" }, 
} 

我想用這個NG-重複。但是「key2」的值必須在他們自己的ng-repeat內迭代。所以像這樣:

<ul ng-repeat="x in myObj"> 
    <li> {{x.key1}} </li> 
    <ul ng-repeat="y in x.key2"> 
     <li></li> 
    </ul> 
    <li> {{x.key3}} </li> 
</ul> 

顯然這是行不通的。 第一陣列的結果應該是這樣的(5鋰元素應該被創建):

<ul> 
    <li> value1 </li> 
    <ul> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> 
    </ul> 
    <li> value 3 </li> 
</ul> 

回答

2

可以創建自定義方法rangerange(n)將返回[1,2,3, .. n]

HTML

<div ng-controller="MainCtrl"> 
<ul ng-repeat="x in myObj"> 

    <li> {{x.key1}} </li> 
    <ul ng-repeat="y in range(x.key2)"> 
     <li></li> 
    </ul> 
    <li> {{x.key3}} </li> 
</ul> 

JS

$scope.myObj = [ 
    {"key1":"value1", "key2":5, "key3":"value3" }, 
    {"key1":"value4", "key2":2, "key3":"value5" }, 
    {"key1":"value6", "key2":4, "key3":"value6" }, 
]; 


$scope.range = function(count){ 
    var items = []; 
    for (var i = 0; i < count; i++) { 
    items.push(i) 
    } 

    return items; 
} 

Demo Plunker

0

在控制器中添加這種方法

$scope.getNumber = function(count){ 
     return new Array(count); 
    } 

和更新您的HTML作爲

<ul ng-repeat="x in myObj"> 
     <li> {{x.key1}} </li> 
     <ul ng-repeat="y in getNumber(x.key2)"> 
      <li></li> 
     </ul> 
    <li> {{x.key3}} </li> 
</ul>