使用 ng-repeat 从对象的 HTTP 响应数组中检索数据



我正在尝试使用控制器中的HTTP get请求从laravel API检索响应,并ng-repeat遍历视图中的所有数据,它会在控制台中记录所有响应,但不在视图中显示任何内容。 这是我的 JSON 对象:

[
{
"id":1,
"product_id":"ABCly119",
"name":"Shirt",
"category_id":"fashion",
"color":"Grey",
"size":"L",
"brand":"Tims",
"type":"Polo",
"price":11000,
"main_image":null,
"vat":null,
"description":"A very good shirt",
"product_condition":"new",
"created_at":"2017-07-31 14:36:17",
"updated_at":"2017-07-31 15:37:21"},
{
"id":2,
"product_id":"ABCly139",
"name":"Shirt",
"category_id":"fashion",
"color":"Black",
"size":"M",
"brand":"Tims",
"type":"Polo",
"price":10000,
"main_image":null,
"vat":null,
"description":"A very good shirt",
"product_condition":"new",
"created_at":"2017-07-31 14:39:47",
"updated_at":"2017-07-31 14:39:47"},
{
"id":3,
"product_id":"ABCly139",
"name":"Shirt",
"category_id":"fashion",
"color":"Blue","size":"S",
"brand":"Tims",
"type":"Polo",
"price":12000,
"main_image":null,
"vat":null,
"description":"A very good shirt",
"product_condition":"new",
"created_at":"2017-07-31 14:41:06",
"updated_at":"2017-07-31 14:41:06"
}
]

这是我的控制器

angular
.module('productsController',[])
.constant('baseUrl', 'http://127.0.0.1:8000/api/product')
.controller('productCtrl',['$scope','$log','$http','baseUrl','$rootScope',function($scope,$log,$http,baseUrl,$rootScope){
$log.info('Product controller loaded');
$http.get(baseUrl + '/fetch')
.then(function (response){
$scope.response = response;
var i = $scope.response;
angular.forEach(i, function(item){
$scope.product = item;
console.log($scope.product);    
});

return response.data;
},function  (error){
$scope.error = error;
$log.info($scope.error);
});
}]);

这是我的观点

<ul>
<li ng-repeat="x in products">
<span>{{x[0].name}}</span>
</li>                       
</ul>

我尝试使用它记录到控制台但未显示在视图上的上面的代码

$scope.product = item 将覆盖除 i 数组的最后一项之外的所有项目,您最好在下面这样做

$scope.products=[];
angular.forEach(i, function(item){
$scope.products.push(item);
});
<ul>
<li ng-repeat="x in products">
<span>{{x.name}}</span>
</li>                       
</ul>

或下面的标记打印名称属性的所有值

<ul>
<li ng-repeat="x in response.data">
<span>{{x.name}}</span>
</li>                       
</ul>

没有 $scope.products,只需 $scope.product,请尝试

<ul>
<li ng-repeat="x in response">
<span>{{x[0].name}}</span>
</li>                       
</ul>

将控制器更改为:

angular
.module('productsController',[])
.constant('baseUrl', 'http://127.0.0.1:8000/api/product')
.controller('productCtrl',['$scope','$log','$http','baseUrl','$rootScope',function($scope,$log,$http,baseUrl,$rootScope){
$log.info('Product controller loaded');
$http.get(baseUrl + '/fetch')
.then(function (response){
$scope.products = response
},function  (error){
$log.info(error);
});
}]);

以及您对以下方面的看法:

<ul>
<li ng-repeat="x in products">
<span>{{x.name}}</span>
</li>                       
</ul>

你应该很高兴。

最新更新