当索引是动态的时,如何访问Ember.js中把手内的数组对象?

时间:2014-06-18 21:48:03

标签: ember.js handlebars.js

我试图在Ember.js上访问车把内的数组内的对象。我尝试了以下组合:

1 {{render "input-validation-message" validity.options.[_view.contentIndex]}}

2 {{render "input-validation-message" validity.options._view.contentIndex}}

3 {{render "input-validation-message" validity.options[_view.contentIndex]}}

数组是validity.options,索引是_view.contentIndex,这是我知道如何在Ember.js上的{{#each}}循环中访问索引的唯一方法。

这三种方法都没有传递对象。有没有人有解决方案?

编辑:

经过一番游戏,我发现_view.contentIndex未在{{unless}}或{{if}}块内访问。我的代码看起来有点像这样:

{{#each modelArray}}
       {{#unless _view.contentIndex}}
        [code here that needs to access _view.contentIndex]
       {{else}}
        [more code here that needs to access _view.contentIndex]
       {{/unless}}
{{/each}}

有没有办法解决这个问题?


固定!

我稍微修改了正确答案:

{{#each item in modelArray itemController='foo'}}
   {{render "input-validation-message" item.validityOption}}
{{/each}}

App.FooController = Ember.ObjectController.extend({
  validityOption: function(){
    var model = this.get('model'),
        eachController = this.get('target'),
        parentController = eachController.get('target'),
        idx = eachController.get('content').indexOf(model);
    return parentController.get('validity.options').objectAt(idx);
  }.property('model')
});

如果数组不是Ember.Array,请使用[]而非objectAt()

1 个答案:

答案 0 :(得分:1)

您想要使用itemController并在控制器中挂钩关联

{{#each item in modelArray itemController='foo'}}
   {{render "input-validation-message" item.validityOption}}
{{/each}}

App.FooController = Ember.ObjectController.extend({
  validityOption: function(){
    var model = this.get('model'),
        parentController = this.parentController,
        idx = parentController.indexOf(model);
    return parentController.get('validity.options').objectAt(idx);
  }.property('model')
});

示例:http://emberjs.jsbin.com/ruzusiya/1/edit