微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在handlebars模板中显示hasMany ember关系中的第一项

我需要在hasMany关系中显示一个项目

基本上一个线程可以有多个作者,但我需要只显示特定模板中的第一个

我有以下的json

{
    threads: [
        {
           id: 1,authors: [2,3]
        }
    ],authors: [
        {
            id: 2,fullname: "foo"
        },{
            id: 3,fullname: "bar"
        }
    ]        
}

以下型号

App.Thread = DS.Model.extend({
    authors: DS.hasMany('author')
});

App.Author = DS.Model.extend({
    fullname: DS.attr('string')
});

现在在我的模板中,我想做一些像{{thread.authors [0] .fullname}}这样的东西,但它不起作用.我根据把手语法尝试了thread.authors.0.fullname,但没有改变.

Thnx提前为您提供帮助

解决方法

使用Ember.Enumerable的 firstObject
{{thread.firstObject.fullName}}

如果要在很多地方使用它,最好将其定义为模型中的计算属性

App.Thread = DS.Model.extend({
  authors: DS.hasMany('author')

  firstAuthor: Ember.computed.alias('authors.firstObject')
});

并在模板中使用它:

{{firstAuthor.name}}

原文地址:https://www.jb51.cc/js/159611.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐