繁体   English   中英

在Ember.js中使用模型数据填充复选框值

[英]Populate checkbox values with model data in Ember.js

我有一个有大量用户的ember应用程序。 这些用户中的每一个都可以与许多主题相关联。 所以我有一个主题模型:

App.Subjects = DS.Model.extend({
  subject         : DS.attr('string'),
});

App.Subject.FIXTURES = [{
  id: 1,
  name: 'Sales',

}, {
  id: 2,
  name: 'Marketing',

}

];

和用户模型:

App.User = DS.Model.extend({
  name         : DS.attr(),
  email        : DS.attr(),
  subjects       : DS.hasMany('subject'),

});

App.User.FIXTURES = [{
  id: 1,
  name: 'Jane Smith',
  email: 'janesmith@thesmiths.com',
  subjects: ["1", "2"]

}, {
  id: 2,
  name: 'John Dorian',
  email: 'jd@sacredheart.com',
  subjects: ["1", "2"]
}

];

我在模板中无法表示这种1:M关系。 我有一个编辑用户模板(Im也用来创建用户),您可以在其中通过复选框选择用户的主题。 但是,我希望这些复选框由subjects模型中的数据驱动。 这可能吗? 我在网上发现的文档很少,并且对余烬开发非常陌生。 这是我的模板:

<script type = "text/x-handlebars" id = "user/edit">

<div class="input-group">
<div class="user-edit">


  <h5>User name</h5>
  {{input value=name}}

  <h5>User email</h5>
  {{input value=email}}

  <h5>Subjects</h5>

{{input type="checkbox" value = "sales" name="sales" checked=sales}}
{{input type="checkbox" value = "support" name="support" checked=support}}

</div>
<button {{action "save"}}> Save </button>
</div>
</script>

编辑:这是我当前的userController.js

App.UserController = Ember.ObjectController.extend({

  deleteMode: false,

  actions: {
    delete: function(){

      this.toggleProperty('deleteMode');
    },
    cancelDelete: function(){

      this.set('deleteMode', false);
    },
    confirmDelete: function(){
      // this tells Ember-Data to delete the current user
      this.get('model').deleteRecord();
      this.get('model').save();
      // and then go to the users route
      this.transitionToRoute('users');
      // set deleteMode back to false
      this.set('deleteMode', false);
    },
    // the edit method remains the same
    edit: function(){ 
      this.transitionToRoute('user.edit');
    }
  }
});

您需要做的是在模板中更改此行:

{{#each subject in user.subject}}
  {{subject.name}},
{{/each}}

为了这:

{{#each subject in user.subjects}}
  {{subject.name}},
{{/each}}

您是否注意到我更改了主题?

并且,我还建议您在App.SubjectController中更改以下代码:

selected: function() {
    var user = this.get('content');
    var subject = this.get('parentController.subjects');
    return subject.contains(user);
}.property()

对此:

selected: function() {
    var subject = this.get('content');
    var userSubjects = this.get('parentController.subjects');
    return userSubjects.contains(subject);
}.property()

这是数据的更好表示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM