我在Angular中显示
JSON数据时遇到了麻烦.我成功地将数据从后端发送到前端(Angular),但我无法显示它们.
我尝试在JSFiddle上模拟类似的情况,尽管我已经从后端准备了数据
获取/发送数据 – >后端方面:
//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',-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() }); }); });
获取数据 – >前端(角度)
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); }); } }])
带有ng-repeat指令的HTML部分:
<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>
谁会知道问题是什么?
解决方法
据我所知,你将对象存储为JSON,但你永远不会解析它.因此使用
$scope.messages = JSON.parse(res);
代替
$scope.messages = res;
应该解决你的问题.
这是你的JSFiddle版本:https://jsfiddle.net/29y61wtg/5/