I have a list of items in an Ember template that looks like:
<ul>
{{#each color in colors}}
<li {{action 'changeColor' color}}>{{color.hexValue}}</li>
{{/each}}
</ul>
In my controller, I have the following:
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');
}
});
When a color is clicked, I'd like to add an active class to the <li>
that corresponds to the clicked item. selectedColor
can also be set to a default color (instead of null), and I'd like the <li>
that has the corresponding color to have the active class on page load.
The other SO questions I've seen have been about how to set the parent element for a {{link-to}}
to active (mostly for Twitter Bootstrap's nav), but in this case I'm not using {{link-to}}
and I'm not doing a route change.
Does anyone know how I can accomplish this?
Your action doesn't work and will alwas set the select color to the string 'newColor'.
Anyway, you can use a computed Property showColors
, that includes the class to be rendered in the template, like this:
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);
}
}
});
( Working example )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.