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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18229908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:07:44  来源:igfitidea点击:

Sails.js - passing data to a view

javascriptnode.jssails.js

提问by vladzam

I've recently started learning how to use Sails.js and I came across a small issue.

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

I have a model called Applicant, as follows:

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

module.exports = {

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

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

  }

};

I have built the index action to return all the instances of the Applicant model:

我已经构建了索引操作来返回申请人模型的所有实例:

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

And this is the view that I am using:

这是我正在使用的视图:

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

    <ul>
        <% for (applicant in apps) { %>
        <li><%= applicant.name %> <%= applicant.email %></li>
        <% } %>
    </ul>
</section>

Still, when I load the corresponding URL, I can't see my data displayed.

尽管如此,当我加载相应的 URL 时,我看不到我的数据显示。

I have read the Sails.js documentation, but I can't seem to find what's wrong with my code.

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

It would be great if someone could help me solve this problem.

如果有人能帮我解决这个问题,那就太好了。

Thank you!

谢谢!

采纳答案by ataman

Try

尝试

<%= apps[applicant].name %>

It's just like forloop works. applicantis an index in appsarray.

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

Edit:Better way is to use javascript array's built in method forEach, because this way you avoid cycling through elements, inherited from apps's type (for example, elements, assigned like this: apps.__proto__.foo = {name: "bar"}or Array.prototype.foo2 = {name: "pi222"}).

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

<% apps.forEach(function(applicant)  { %>
    <li><%= applicant.name %> <%= applicant.email %></li>
<% }); %>

P.S. Of course this javascript's method (forEach) wouldn't work in IE <= 8(if you consider to use it in browser). Butwe are inside NodeJs, which is built on top of V8 engine. So this will work, anyway.

PS 当然,这个 javascript 的方法 ( forEach) 在 IE <= 8 中不起作用(如果你考虑在浏览器中使用它)。但是我们在 NodeJs 内部,它构建在 V8 引擎之上。所以无论如何这都会起作用。