Binding to model in template based on a list of st

2019-08-07 09:24发布

In my controller I have a list of strings like this:

columns : ['name', 'description']

I want to filter what is displayed in the template based on this list:

        {{#each m in controller.model}}
            {{#each col in controller.columns}}
               <td>{{m[col]}}</td>
            {{/each}}
        {{/each}}

Of course {{m[col]}} is not valid code but you get the idea. How might I achieve this?

This code is generic so I have no way of telling what the columns array contains before hand.

标签: ember.js
2条回答
Explosion°爆炸
2楼-- · 2019-08-07 10:02

You can create a bound helper as follows:

Ember.Handlebars.registerBoundHelper('dd', function(rowData, col) {
  return rowData[col];
});

Then, you can use it in your template as follows:

{{#each item in model}}
  <tr>
    {{#each col in columns}}
      <td> {{ dd item col }} </td>
    {{/each}}
  </tr>
{{/each}}

Working example on jsbin here

查看更多
Lonely孤独者°
3楼-- · 2019-08-07 10:05

If you want the data bound to the template so that it updates when the data changes, use a small component as follows:

App.getPropertyComponent = Ember.Component.extend({
    tagName: '',

    value: function() {
        var model = this.get('model');
        var method = this.get('method');

        return model[method];

    }.property('model.{name,description}')
});

Notice that you have to manually specify each property you are binding to.

Component template:

{{value}}

Then, you can use it in your template as follows:

{{#each item in model}}
  <tr>
    {{#each col in columns}}
      <td>{{get-property model=item method=col}}</td>
    {{/each}}
  </tr>
{{/each}}
查看更多
登录 后发表回答