Saturday 3 June 2017

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> </td>
      <td> </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!



via El Fred

No comments:

Post a Comment