2017-02-19 126 views
1

我在Ember中渲染一些模型参数,它应该像复选框一样。因此点击元素的css类应该改变,以指示状态(例如,活动时为绿色)。 目前所有渲染的元素只有一个被点击时才会改变他们的类。 我怎样才能改变真正点击元素的CSS类?我以为这会照顾到这一点。Ember |设置特定元素的css类

这是我的视图模板:

{{#each model as |attributes|}} 
    {{#each attributes.identifiers as |identifier| }} 
    <div class="col-element"> 
     <div class="checkelement {{state}}" {{action "includeToExport" identifier}}> 
     <p>{{identifier}}</p> 
     </div> 
    </div> 
    {{/each}} 
{{/each}} 

,在控制器的动作:

includeToExport: function(identifier){ 
var state = this.get('state'); 
if (state == 'activated'){ 
    this.set('state',''); 
    // and do something with identifier 
} 
else { 
    this.set('state', 'activated'); 
    // and do something with identifier 
}}, 

的是,CSS:

.checkelement.activated {background-color:#4CAF50; } 

感谢您的帮助!

回答

1

如果您希望为每个项目具有单独的状态,则可以选择一种方法创建一个组件,该组件将表示每个标识符并将状态控件移动到那里。您可以将其视为将{{#each}}...{{/each}}之间的所有代码移动到其自己的组件中。这将允许你封装状态控制每个标识符:

{{#each model as |attributes|}} 
    {{#each attributes.identifiers as |identifier| }} 
    {{my-identifier identifier=identifier 
        includeToExportAction=(action "includeToExport")}} 
    {{/each}} 
{{/each}} 

组件看起来像

// components/my-identifier 
export default Ember.Component.extend({ 
    // passed in 
    identifier: null, 
    includeToExportAction: null, 

    // local 
    state: '', // <-- here you set the initial value for the state 
    classNames: ['col-element'], 

    actions: { 
    setState() { 
     // state-control is now local to each component 
     // and thus unique for each identifier 
     const state = this.get('state'); 
     if (state == 'activated'){ 
     this.set('state',''); 
     } else { 
     this.set('state', 'activated') 
     } 

     // send the identifier and the updated state to the parent 
     this.get('includeToExportAction')(
     this.get('state'), 
     this.get('identifier') 
    ) 
    } 
    } 
}); 

模板组件

// templates/components/my-identifier 
<div class="checkelement {{state}}" {{action "setState"}}> 
    <p>{{identifier}}</p> 
</div> 

现在你的控制器就不需要在includeToExport中设置任何状态,因为它现在从my-identifier组件传递过来:

includeToExport(identifier, state){ 
    if (state == 'activated'){ 
    // do something with identifier 
    } 
    else { 
    // do something with identifier 
    } 
}