如何在创建新元素时从每个循环中调用一个动作?

How to call a action from each loop while create a new element?

我要求根据索引添加一个class名称。我也确实有许多其他条件事件要添加到每个元素中。出于这个原因,我想在元素创建时添加一个回调。

如何从每个迭代器中调用一个函数。我这样试过:

{{#each model as |flower index|}}
    <li class="(action 'setting()')">{{flower}}</li> //trying to call
{{/each}}

这是我的控制器:

actions:{
    setting:function(element, index){
        console.log(element, index); // i will add class name by condition
    }
  }

可能吗?或者什么是正确的方法?特别是我需要根据索引值添加不同的 css classes。 (想法)

Live Example

有几种方法可以做到这一点。我更愿意创建一个像这样使用的自定义组件:

{{#each model as |flower index|}}
  {{flower-item flower=flower index=index}}
{{/each}}

您的自定义组件可能如下所示:

// Imports

export default Component.extend({
  // Inputs
  flower: null,
  index: 0,

  tagName: 'li',
  classNameBindings: ['flowerClass'],

  flowerClass: computed('index', function() {
    return 'flower-' + get(this, 'index');
  })
});

见小游戏:flower-item component