簡體   English   中英

Angular JS和Express項目:將對象傳遞給ejs視圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM