我有一个包含许多用户的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关系时遇到问题。我有一个编辑用户模板(我也用来创建用户),您可以通过复选框选择用户的主题。但是,我希望这些复选框由我的subjects
模型中的数据驱动。这可能吗?我在网上找到了很少的文档,对于ember开发来说我是一个新手。这是我的模板:
<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');
}
}
});
答案 0 :(得分:1)
您需要做的是在模板中更改此行:
{{#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()
这是对数据的更好表示。