Reputation: 147
I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/site.css" />
<!--<script src="js/script.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-model="array"></p>
<input type="text" ng-model="product" />
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Image</th>
</tr>
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.price }}</td>
<td>{{ product.image }}</td>
</tr>
</table>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl',
function callController($scope) {
fetch('js/adds.json').then(function (response) {
return response.json();
}).then(function (data) {
var jproducts = data["products"];
for (var i = 0; i < jproducts.length; i++) {
$scope.products = [
{
name: jproducts[i]["name"],
description: jproducts[i]["description"],
price: jproducts[i]["price"],
image: jproducts[i]["image"]
}
];
}
});
});
</script>
</div>
</body>
</html>
And here is the JSON file:
{
"products" : [
{ "name" : "Porsche Bike", "description" : "A bike with a brand name!", "price" : 10000, "image" : "bike.jpg" },
{ "name" : "Pretty Shoes", "description" : "Come to our shoe store", "price" : 54.45, "image" : "shoes.jpg" },
{ "name" : "Pie Fest!", "description" : "Oh yeah this is officially the best pie ever", "price" : 3.45, "image" : "pie.jpg" },
{ "name" : "Inside Out Umbrella", "description" : "Designer Umbrellas for low cost", "price" : 14.55, "image" : "umbrella.jpg" },
{ "name" : "Coffee", "description" : "Come get your morning dessert", "price" : 4.59, "image" : "coffee.jpg" }
]
}
What I need is for the JSON to be displyed into a table. However, so far it only displays this:
Coffee Come get your morning dessert 4.59 coffee.jpg
How can I get it to display all the products? And also it only displays something when I type something into the text input.
Upvotes: 1
Views: 100
Reputation: 222542
You do not have to iterate over producs inside the controller. Simply assign it as
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get('adds.json').
then(function(response) {
$scope.products = response.data.products;
});
});
Upvotes: 2