Sails.js - 将数据传递给视图

vla*_*zam 11 javascript node.js sails.js

我最近开始学习如何使用Sails.js,我遇到了一个小问题.

我有一个名为申请人的模型,如下:

module.exports = {

  attributes: {     
     name: {
      type: 'STRING',
      required: true
     },

     email: {
      type: 'STRING',
      required: true
     }

  }

};
Run Code Online (Sandbox Code Playgroud)

我构建了索引操作以返回Applicant模型的所有实例:

module.exports = {
    index: function(req, res) {
        Applicant.findAll().done(function(err, applicants) {
            res.view({
                apps: applicants
            });
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的观点:

<section id="applicants">
    <h1>List of applicants</h1>

    <ul>
        <% for (applicant in apps) { %>
        <li><%= applicant.name %> <%= applicant.email %></li>
        <% } %>
    </ul>
</section>
Run Code Online (Sandbox Code Playgroud)

但是,当我加载相应的URL时,我看不到我的数据显示.

我已经阅读了Sails.js文档,但我似乎无法找到我的代码有什么问题.

如果有人可以帮助我解决这个问题,那就太棒了.

谢谢!

ata*_*man 10

尝试

<%= apps[applicant].name %>
Run Code Online (Sandbox Code Playgroud)

就像for循环工作一样.applicantapps数组中的索引.

编辑:更好的方法是使用javascript数组的内置方法forEach,因为这样你就可以避免循环使用从apps类型继承的元素(例如,元素,像这样分配:apps.__proto__.foo = {name: "bar"}或者 Array.prototype.foo2 = {name: "pi222"}).

<% apps.forEach(function(applicant)  { %>
    <li><%= applicant.name %> <%= applicant.email %></li>
<% }); %>
Run Code Online (Sandbox Code Playgroud)

PS当然这个javascript的方法(forEach)在IE <= 8中不起作用(如果你考虑在浏览器中使用它).我们在NodeJs里面,它建立在V8引擎之上.无论如何,这将是有效的.