在 Ember 中,我有两个模型,产品和流派,产品有很多流派,设置如下。
App.Product = DS.Model.extend({
title: DS.attr(),
genres: DS.hasMany('genre')
});
App.Genre = DS.Model.extend({
name: DS.attr(),
product: DS.belongsTo('product')
});
可以在单独的页面上创建流派,然后可以通过从选择元素中进行选择来为产品页面上的产品设置多个流派,并可以选择添加额外的流派。 Controller 和模板设置如下。
App.ProductController = Ember.ObjectController.extend({
availableGenres: function() {
return this.store.findAll('genre');
}.property(),
actions: {
saveProduct: function() {
var product = this.get('model');
product.save();
},
addGenre: function() {
var product = this.get('model');
var genre = this.store.createRecord('genre');
product.get('genres').pushObject(genre);
}
}
});
模板:
{{#each genre in genres}}
{{view "select" content=availableGenres value=genre.name}}
{{/each}}
<button {{action 'addGenre'}}>Add Genre</button>
通俗地说,addGenre 函数应该向 UI 添加新的选择,允许用户从预定义的流派集中进行选择。
目前的设置方式会创建一个新的流派,这是不正确的。我无法解决的是我应该如何在 View 中创建一个新的流派选择,而不创建一个新的流派。
如何在不创建新流派的情况下为流派创建新选择?将其设置为 possibleGenres 中的第一个流派就足够了,但我一直在研究如何在该函数中选择第一个流派。我对 Ember 还很陌生,因此非常感谢任何帮助!
最佳答案
这是因为你的 addGenre 创建了新的流派...:)
addGenre: function() {
var product = this.get('model');
var genre = this.store.createRecord('genre'); //here you create a new genre
product.get('genres').pushObject(genre); //and then you push the object
}
来自 select doc您的选择应如下所示:
{{view "select"
content=availableGenres
optionValuePath="content"
optionLabelPath="content.name"
value=selectedGenre}}
那么你只需修改你的 addGenre 方法
addGenre: function() {
this.get('model.genres').pushObject(this.get('selectedGenre'));
//and eventually persist save by making a this.get('model').save() :)
}
编辑在第一个 View 后选择添加以下内容
{{#each genre in model.genres}}
{{view "select"
content=availableGenres
optionValuePath="content"
optionLabelPath="content.name"
value=genre}}
{{/each}}
它的作用是,每次您单击调用 addGenre 操作时,它都会将此“流派”添加到您的对象中,每个流派仅列出对象中已有的流派,并允许您即时编辑它们。
关于javascript - Ember 添加有许多子模型可供从下拉列表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892431/