对json中的对象数组进行ng-repeat

时间:2017-04-11 07:18:06

标签: angularjs json angularjs-ng-repeat

我一直在尝试在远程JSON文件的表中显示nameaddress等对象字段。我似乎无法弄清楚我做错了什么。 ng-repeat仅在索引迭代器时才有效。

angular.module('mainApp', [])
.controller('branchListCtrl', function($scope, $http) {
  $http.get('http://some.url.com')
  .then(function(response) {              
    $scope.artists = response.data;
    console.log($scope.artists);
  });
});

<tr ng-repeat="x in artists"> 
  <td>{{x.name}}</td> <!--this only gives empty rows equal to # of objectsin json-->
  <td>{{x.address}}</td>
</tr>    
<tr ng-repeat="x in artists">
  <td>{{x[1].name}}</td>
  <td>{{x[1].address}}</td>
</tr> 

5 个答案:

答案 0 :(得分:1)

控制器中的

应该是:

$scope.artists = response.data.data;

答案 1 :(得分:1)

你错过了.data。试试这个:

<tr ng-repeat="artist in artists.data"> 
   <td>{{artist.name}}</td>
     <td>{{artist.address}}</td>
</tr>

答案 2 :(得分:0)

&#13;
&#13;
var app = angular.module('myApp',[]);

app.controller('ctrl', function($scope){

$scope.datas = {"success":"yes", "data":[ { "id":"1", "parent_retailer":1, "name":"dummy", "address":"1234d", "status":true, "geo_location":{ "x":24.321, "y":74.102 } }, { "id":"2", "parent_retailer":1, "name":"dummy2", "address":"fdsds", "status":true, "geo_location":{ "x":24.321, "y":74.102 } }, ], "error_code":"", "error_description":"" };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ctrl">
<div ng-repeat="dat in datas.data">
{{dat.id}} {{dat.name}} {{dat.address}}  {{dat.geo_location.x}}
</div>

</div>
</body>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

对于Json对象您需要在ng-repeat

中使用键值
<tr ng-repeat="(key, value) in artists"> 
 <td>{{key}}</td> 
 <td>{{value}}</td>
</tr>    

你可以在这里参考: http://docs.angularjs.org/api/ng.directive:ngRepeat

答案 4 :(得分:0)

您的代码运行正常。无需额外添加 ng-repeat

<强>样本

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.artists = [{
	"id": "1",
	"parent_retailer": 1,
	"name": "dummy",
	"address": "1234d",
	"status": true,
	"geo_location": {
		"x": 24.321,
		"y": 74.102
	}
}, {
	"id": "2",
	"parent_retailer": 1,
	"name": "dummy2",
	"address": "fdsds",
	"status": true,
	"geo_location": {
		"x": 24.321,
		"y": 74.102
	}
}];
});
table,tr,td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table>
  <tr>
    <td>Name</td>
    <td>Address</td>
  </tr>
  <tr ng-repeat="x in artists"> 
    <td>{{x.name}}</td>
    <td>{{x.address}}</td>
  </tr>
</table>
</div>