2016-07-14 95 views
0

我有一个具体的要求显示顺序,其中json数据来源是这样的:角:NG-重复表中的

[{Id : "a", Name : "John", age : 50}, 
{Id : "b", Name : "Bob", age : 40}] 

我想表明它使用ng-repeat表,但在某种程度上,其中头如下所示:

<table> 
    <tr> 
    <td>Id</td> 
    <td>a</td> 
    <td>b</td> 
    </tr> 
    <tr> 
    <td>Name</td> 
    <td>John</td> 
    <td>Bob</td> 
    </tr> 
    <tr> 
    <td>Age</td> 
    <td>50</td> 
    <td>40</td> 
    </tr> 
</table> 

有没有办法使用angularjs来实现这个?

感谢

回答

1

只要你有一个控制器:然后

angular.module('MyApp', []) 
.controller('MyController', function($scope) { 
    $scope.data = [ 
     {Id : "a", Name : "John", age : 50}, 
     {Id : "b", Name : "Bob", age : 40} 
    ]; 
}); 

您的标记将如下所示。如果数据是不会更改其显示后:

<table> 
    <tr> 
     <td>Id</td> 
     <td ng-repeat="item in ::data">{{::item.Id}}</td> 
    </tr> 
    <tr> 
     <td>Name</td> 
     <td ng-repeat="item in ::data">{{::item.Name}}</td> 
    </tr> 
    <tr> 
     <td>Age</td> 
     <td ng-repeat="item in ::data">{{::item.age}}</td> 
    </tr> 
</table> 

如果数据都显示后,它改变,并且希望以相应的更新,则:

<table> 
    <tr> 
     <td>Id</td> 
     <td ng-repeat="item in data track by $index">{{item.Id}}</td> 
    </tr> 
    <tr> 
     <td>Name</td> 
     <td ng-repeat="item in data track by $index">{{item.Name}}</td> 
    </tr> 
    <tr> 
     <td>Age</td> 
     <td ng-repeat="item in data track by $index">{{item.age}}</td> 
    </tr> 
</table> 
0

您可以将您的阵列中的一个对象,那么你可以考虑使用嵌套NG-重复,如下图所示:

(function() { 
 
    "use strict"; 
 
    angular.module('app', []) 
 
    .controller('mainCtrl', function($scope) { 
 
     var array = [ 
 
     { 
 
      "Id":"a", 
 
      "Name":"John", 
 
      "age":50 
 
     }, 
 
     { 
 
      "Id":"b", 
 
      "Name":"Bob", 
 
      "age":40 
 
     } 
 
     ]; 
 
     
 
     // If you're sure that the properties are always these: 
 
     $scope.mainObj = { 
 
     "Id": [], 
 
     "Name": [], 
 
     "age": [] 
 
     }; 
 
     
 
     // If you're unsure what are the properties: 
 
     /* 
 
     $scope.mainObj = {}; 
 
     Object.keys(array[0]).forEach(function(value) { 
 
     $scope.mainObj[value] = []; 
 
     }); 
 
     */ 
 

 
     // Iterates over its properties and fills the arrays 
 
     Object.keys($scope.mainObj).forEach(function(key) { 
 
     array.map(function(value) { 
 
      $scope.mainObj[key].push(value[key]); 
 
     }) 
 
     }); 
 
    }); 
 
})();
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> 
 
</head> 
 

 
<body ng-controller="mainCtrl"> 
 
    <table> 
 
    <tr ng-repeat="(key, values) in mainObj track by $index"> 
 
     <td ng-bind="key"></td> 
 
     <td ng-repeat="value in values track by $index" ng-bind="value"></td> 
 
    </tr> 
 
    </table> 
 
</body> 
 

 
</html>

我希望它有帮助!