【问题标题】:cant get the model value in template无法在模板中获取模型值
【发布时间】:2015-11-29 16:43:48
【问题描述】:

刚开始玩 emberjs。不知道这是一个愚蠢的问题还是一个好问题,但我被困在这个问题上几天了,不知道为什么。

在我的 router.js 中

Router.map(function() {
  this.resource('posts', {path: '/'});
  ..........
  });

  .....
  this.resource('post', {path: 'posts/:post_id'});
});

在路由文件夹中,posts.js 设置如下。它有简单的 js 变量,用于保存文章的 id、标题和正文。

export default Ember.Route.extend({
    model: function(){
         var posts = [
        {
        id:'1',
        title:'lipsome vesicle',
        body:"A liposome is a spherical vesicle"},      
        {
        id:'2',
        title:'another lipsome vesicle',
        body:"A liposome is a another vesicle"}
]
    //console.log(posts)
        return posts;
    }
});

在posts.hbs 中,每个帖子的标题显示为指向帖子的链接。当然,通过 每个模型作为 |post| 循环并打印指向 post.title 的链接。

我的 post.js 文件只是获取帖子的模型并返回它。

export default Ember.Route.extend({

    model: function(params) {

        return this.modelFor('posts').findBy('id', params.post_id);
    }
});

在我的 post.hbs 模板中,我想简单地显示帖子的标题和正文。如果它像 post.title 或类似的东西,它会更可红色。但我看到了一些教程。

 <h1>{{title}}</h1>
    <h1>{{body}}</h1>

url 转到 localhost:4200/post/1 但我看不到标题和正文

当我检查控制台中的值时

 this.modelFor('posts').findBy('id', params.post_id).title , it prints the title

但是视图是空白的。 我在某处读到,控制器是负责从模型中获取值的控制器。在那种情况下,我也不知道如何访问该控制器中返回的模型。

我看过很多教程,包括 railscast 的 raffler example,因为我有 Rails 的背景。但是那些包括很多其他的 tuts 似乎已经过时了。所以对于所有新学习者来说,这也是令人沮丧和困惑的。 除了 emberjs 指南还有什么新鲜的好资源吗?

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    由于标题是在控制台中打印的,经过多次尝试,当我尝试这个技巧时,我终于设法在单个帖子中获得我的标题。当我单击 $E 控制台时使用 Ember 检查器插件给了我所有的帖子。所以我将该对象放入数组并返回该数组。

    model: function(params) {
            // console.log("hell")
             console.log(this.modelFor('posts').findBy('id', params.post_id).title);
             var post = [this.modelFor('posts').findBy('id', params.post_id)];
            return post;
        }
    

    然后在我看来,我循环遍历数组:

    <ul>
        {{#each model as |post|}}
            <li>{{post.title}}</li>
        {{/each}}
    </ul>
    

    但我想知道更好的方法。

    【讨论】:

      猜你喜欢
      • 2019-06-18
      • 2013-06-10
      • 2019-12-03
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      相关资源
      最近更新 更多