我在循环中选择视图,我想在下拉列表中设置默认选择。我尝试设置"值"属性以及"选择"属性,但没有任何效果。我试图创建 jsbin 来演示这个问题,但它给了我完全不同的问题,但我在我的开发代码中没有看到这个问题。
我的控制器定义如下:
App.AnswerController = Ember.ObjectController.extend({
answerLayouts: function () {
return this.get('store').findAll('layout');
}.property(),
selectedAnswerLayout: null,
initialize: function () {
this.set('selectedAnswerLayout', this.get('store').find('layout', this.get('id')));
}.on('init')
});
在我正在做的模板中:
<table>
{{#each answers itemController="answer"}}
<tr>
<td>{{name}}</td>
<td>{{view Ember.Select
content=answerLayouts
optionValuePath="content.name"
optionLabelPath="content.displayName"
class="form-control"
prompt="Answer Layout"
selection=selectedAnswerLayout}}
</td>
</tr>
{{/each}}
</table>
并且没有将 answerLayouts 视为数组,但是当我检查 {{answerLayouts.length}} 时,它返回 3!
下面是演示该问题的 jsbin 链接:http://jsbin.com/AcUPIpEl/1/
这是旧版本的 Ember 的问题,它被修复在 1.0+ 和 1.2 之间
http://emberjs.jsbin.com/ODaKIjIw/1/edit
Ok 必须以不同的方式做事才能让事情正常工作。我没有将"answerLayouts"定义为属性,而是将其定义为数组,当控制器初始化时,我填充了数组并在那里设置了 selectedAnswerlayout,如下所示:
App.AnswerController = Ember.ObjectController.extend({
answerLayouts: Ember.A(),
selectedAnswerLayout: null,
initialize: function () {
var self = this,
selectedlayoutId = this.get('id');
this.get('store').find('layout').then(function(data){
data.forEach(function(layout){
self.get('answerLayouts').pushObject(layout);
if(layout.get('id') === selectedlayoutId){
self.set('selectedAnswerLayout',layout);
}
});
});
}.on('init')
});
这是有效的jsbin链接:emberjs.jsbin.com/ODaKIjIw/3。我已经意识到,当我们可以在 init 中定义事物时,最好在那里这样做。我以前在依赖计算属性时遇到过绑定问题。:)吸取的教训