2017-02-19 60 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 
    } 
}