2017-06-03 29 views
0

我有一个Express项目,我正在从Mongo数据库读取数据。我希望能够看到数据库中的所有条目浏览到http://localhost:8080/viewreplies时。Angular JS和Express项目:将对象传递给ejs视图

这部分在“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 }); 
}); 

当我去到本地主机:端口路径中,执行console.log命令打印完整的对象到控制台,所以检索看起来不错。

然后我渲染'回复'视图,它应该列出所有数据。这里是来自'answers.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 is not defined

有人能来看看,看看我在做什么错在这里?非常感谢!

回答

0

你需要使这样的回调里面的视图。异步函数采用在异步过程完成后执行的回调函数。

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 }); 
    }); 

}); 

你也是采用了棱角分明来处理服务器这是错误的数据,

ng-repeat="reaply in allreplies"

你需要使用EJS来throught数据处理和生成的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> 
+0

好极了!谢谢!我太匆忙地开始使用角度(我喜欢HTML格式化),并没有意识到我在ejs上工作。哎呀。现在一切都清楚了! –

+0

@ElFred如果有帮助,那么你能接受我的回答吗? – nrgwsth