2017-06-03 32 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