[英]How do I add an active class to a list of items when an item is clicked on in Ember?
我在Ember模板中有一个项目列表,如下所示:
<ul>
{{#each color in colors}}
<li {{action 'changeColor' color}}>{{color.hexValue}}</li>
{{/each}}
</ul>
在我的控制器中,我具有以下内容:
Ember.Controller.extend({
selectedColor: null,
colors: [
{ 'name': 'black', 'hexValue': '000000' },
{ 'name': 'white', 'hexValue': 'ffffff' },
{ 'name': 'red', 'hexValue': 'ff0000' }
],
actions: {
changeColor: function(newColor) {
this.set('selectedColor', 'newColor');
}
});
单击颜色后,我想向<li>
添加一个与单击的项目相对应的活动类。 selectedColor
也可以设置为默认颜色(而不是null),我希望具有相应颜色的<li>
在页面加载时具有活动类。
我见过的其他SO问题是关于如何将{{link-to}}
的父元素设置为活动的(主要是Twitter Bootstrap的nav),但是在这种情况下,我没有使用{{link-to}}
,但我没有更改路线。
有人知道我该怎么做吗?
您的操作无效,将选择颜色设置为字符串“ newColor”。
无论如何,您可以使用计算所得的属性showColors
,其中包括要在模板中呈现的类,如下所示:
App.IndexController = Ember.Controller.extend({
selectedColor: null,
colors: [
{ 'name': 'black', 'hexValue': '000000' },
{ 'name': 'white', 'hexValue': 'ffffff' },
{ 'name': 'red', 'hexValue': 'ff0000' }
],
showColors: Ember.computed('colors', 'selectedColor', function(){
var that = this;
return this.get('colors').map(function(color){
return {
'name': color.name,
'hexValue': color.hexValue,
'class': (color.hexValue == that.get('selectedColor.hexValue')) ? 'active' : ''
};
});
}),
actions: {
changeColor: function(newColor) {
this.set('selectedColor', newColor);
}
}
});
( 工作示例 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.