Reputation: 345
When testing the code below the query returns the correct data but when I try to display the return data it does not display in my table. If I simply copy the return data and make that the value of $scope.products it displays just fine. Is there something special that have to do to the dynamic data to get it to work? I am new to angularjs so I am still learning.
Return JSON data
{NAME: "21st Amendment Blood Orange IPA", ID: 327},{NAME: "3 Daughters Blonde", ID: 328},{NAME: "90 Shillings", ID: 329},{NAME: "Avrey Ellie's Brown", ID: 330},{NAME: "Bed Head Red Ale", ID: 331},{NAME: "Bell's Two Hearted", ID: 332},{NAME: "Berkshire Steel Rail", ID: 333}
angularjs code
var app = angular.module("root", [])
app.controller("repeater", ["$scope", "$http", function($scope, $http) {
$http({method: 'GET', url: 'http://server/angularjs/cfc/sqldata.cfc?method=products'})
.then(function (response) {
var str = '[';
for(var i in response.data){
str += '{NAME: ' + '"' + response.data[i].NAME + '", ID: ' + response.data[i].ID + '},';
}
str += ']';
//console.log(str);
$scope.products = str;
//document.write(str);
});
}]);
HTML code
<div ng-controller="repeater">
<table border="1" bordercolor="#000000" cellpadding="0" cellspacing="0">
<thead>
<tr>
<td style="font-weight:bold">Index</td>
<td style="font-weight:bold">Item Id</td>
<td style="font-weight:bold">Item Name</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products track by $index" ng-class="{oddRow: $odd}">
<td>{{$index}}</td>
<td>{{product.ID}}</td>
<td>{{product.NAME}}</td>
</tr>
</tbody>
</table>
</div>
Upvotes: 0
Views: 80
Reputation: 204
You shouldn't need to reconstruct your JSON or parse it. You can take the data directly off of the response object like this: response.data.
Take a look a this example:
var app = angular.module('app', []);
app.controller('postController', ['$scope', '$http', function($scope, $http){
$scope.data = 'empty';
$scope.runAJAX = function(){
$http.get('https://jsonplaceholder.typicode.com/posts').then(function(response){
$scope.data = response.data;
}).catch(function(error){
console.log(error);
});
}
}]);
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body ng-controller="postController">
<div>
<input type="button" value="run" ng-click="runAJAX()" />
</div>
<div>
<table>
<tr>
<th>id</th>
</tr>
<tr ng-repeat="post in data">
<td>{{post.id}}</td>
</tr>
</table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>
Upvotes: 1