当在 Ember 中单击项目时,如何将活动的 class 添加到项目列表?
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>
添加一个活动的 class。 selectedColor
也可以设置为默认颜色(而不是 null),我希望具有相应颜色的 <li>
在页面加载时具有活动的 class。
我看到的其他 SO 问题是关于如何将 {{link-to}}
的父元素设置为活动的(主要用于 Twitter Bootstrap 的导航),但在这种情况下我我没有使用 {{link-to}}
,我也没有改变路线。
有谁知道我怎样才能做到这一点?
您的操作无效,并且总是将 select 颜色设置为字符串 'newColor'。
无论如何,您可以使用计算的 属性 showColors
,其中包括要在模板中呈现的 class,如下所示:
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);
}
}
});
我在 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>
添加一个活动的 class。 selectedColor
也可以设置为默认颜色(而不是 null),我希望具有相应颜色的 <li>
在页面加载时具有活动的 class。
我看到的其他 SO 问题是关于如何将 {{link-to}}
的父元素设置为活动的(主要用于 Twitter Bootstrap 的导航),但在这种情况下我我没有使用 {{link-to}}
,我也没有改变路线。
有谁知道我怎样才能做到这一点?
您的操作无效,并且总是将 select 颜色设置为字符串 'newColor'。
无论如何,您可以使用计算的 属性 showColors
,其中包括要在模板中呈现的 class,如下所示:
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);
}
}
});