[英]Angular JS and Express project: passing on object to ejs view
我有一个Express项目,正在从Mongo数据库中读取数据。 浏览到http:// localhost:8080 / viewreplies时,我希望能够看到数据库中的所有条目。
“ index.js”视图中的这部分工作正常:
app.get('/viewreplies', function(req, res) {
// allreplies contains the data from the MongoDB
var allreplies = RepliesModel.find().then(function(result){
console.log(result);
return result;
});
res.render('replies', { allreplies : allreplies });
});
当我转到localhost:port路径时,console.log命令将完整对象打印到控制台,因此检索看起来不错。
因此,然后渲染“回复”视图,该视图应列出所有数据。 这是来自“ replies.ejs”的相关示例。
<body ng-app="myApp" ng-controller="contr">
<h1>Overview of all the results:</h1>
<br>
<table>
<th>Name:</th>
<th>Gender:</th>
<tr ng-repeat="reply in allreplies">
<td> {{ reply.name }}</td>
<td> {{ reply.gender }}</td>
</tr>
</table>
<script>
var app = angular.module('myApp', []);
app.controller('contr', function($scope) {
$scope.allreplies = allreplies;
});
</script>
</body>
看来我没有正确将对象传递给渲染视图。 浏览器控制台状态
ReferenceError:未定义allreplies
有人可以看看我在做什么错吗? 非常感谢!
您需要像这样在回调内部呈现视图。 异步函数采用在异步过程完成后执行的回调。
app.get('/viewreplies', function(req, res) {
// allreplies contains the data from the MongoDB
RepliesModel.find().then(function(result){
console.log(result);
res.render('replies', { allreplies : results });
});
});
另外,您正在使用angular在服务器上处理数据,这是错误的,
ng-repeat="reaply in allreplies"
您将需要使用ejs处理整个数据并生成html。 然后,您将响应发送给客户端。 Angular是通过浏览器而不是服务器使用的。
在您的ejs模板中尝试类似的操作,
<body>
<h1>Overview of all the results:</h1>
<br>
<table>
<th>Name:</th>
<th>Gender:</th>
<% for(var i=0; i<allreplies.length; i++) {%>
<tr>
<td><%= allreplies[i].name %></td>
<td><%= allreplies[i].gender %></td>
</tr>
<% } %>
</table>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.