简体   繁体   中英

Angular JS and Express project: passing on object to ejs view

I have an Express project, in which I am reading data from a Mongo database. I want to be able to see all entries in the database when browsing to http://localhost:8080/viewreplies .

This part in the "index.js" view appears to be working ok:

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

When I go to the localhost:port path, the console.log command prints the full object to the console, so the retrieval looks ok.

So then I am rendering the 'replies' view, which should list all data. Here is the concerned sample from '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>

It seems I am not correctly passing on the object to my rendering view. The browser console states

ReferenceError: allreplies is not defined

Could someone take a look to see what I am doing wrong here? Many thanks!

You need to render the view inside the callback like this. Asynchronous function take the callback which is executed after async process is completed.

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

});

Also you are using angular to process your data on server which is wrong,

ng-repeat="reaply in allreplies"

You'll need to use ejs to process throught the data and generate the html. Then you'll send the response to client. Angular is used from the browser not from the server.

Try something like this in your ejs template,

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM