I have a trouble with displaying JSON data in Angular. I successfully send data from backend to frontend (Angular), but I cannot display them.
I tried to simulate a similar situation on JSFiddle, although I already have prepared data from backend
get/send data -> Backend side:
//push data to Redis
var messages= JSON.stringify(
[
{
"name": "Msg1",
"desc": "desc Msg1"
},
{
"name": "Msg2",
"desc": "desc Msg2"
},
{
"name": "Msg3",
"desc": "desc Msg3"
},
{
"name": "Msg4",
"desc": "desc Msg4"
}
]);
redisClient.lpush('list', messages, function (err, response) {
console.log(response);
});
//get from redis and send to frontend
app.get('/messages', function(req, res){
// Query your redis dataset here
redisClient.lrange('list', 0, -1, function(err, messages) {
console.log(messages);
// Handle errors if they occur
if(err) res.status(500).end();
// You could send a string
res.send(messages);
// or json
// res.json({ data: reply.toString() });
});
});
get data -> frontend (Angular)
angular.module('app')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
'use strict';
getFromServer();
function getFromServer(){
$http.get('/messages')
.success(function(res){
$scope.messages= res;
console.log(res);
});
}
}])
HTML part with ng-repeat directive:
<div ng-app="app" ng-controller="MainCtrl" class="list-group">
<div class="list-group-item" ng-repeat="item in messages">
<h4 class="list-group-item-heading">{{item.name}}</h4>
<p class="list-group-item-text">{{item.desc}}</p>
<div>
</div>
Would anyone know what the problem is?
As far as I can see, you're storing your Object as JSON, but you never parse it. Therefore using
$scope.messages = JSON.parse(res);
instead of
$scope.messages = res;
should fix your problem.
Here is a working JSFiddle version of yours: https://jsfiddle.net/29y61wtg/5/
Note, that this doesn't include a $http call, if you're still having problems after using $http, tell me in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With