Ember.js 如何从 JSON 数组中填充多个单选按钮?

3

我将尝试在{{#each}}块中使用给定的JSON数组填充多个单选按钮。

我的单选按钮视图:

Ember.View.extend({
    tagName: "input",
    type: "radio",
    attributeBindings: ["name", "type", "value", "checked:checked:"],
    click: function() {
        this.set("selection", this.$().val());
    },
    checked: function() {
        return this.get("value") == this.get("selection");
    }.property()
});

模板:

{{#each shippingOptions}}   
    {{view "radiobutton" id=id name="shippingCosts" selectionBinding="choosenShippingCosts" value=id}}
    <label {{bind-attr for=id}}>{{label}}</label>
{{/each}}

控制器:

choosenShippingCosts: 'tomorrow',

shippingOptions JSON数组:

[
   {
      "id":"tomorrow",
      "value":1,
      "label":"wednesday 16 april shipped on market day (€1)"
   },
   {
      "id":"marketPickup",
      "value":0,
      "label":"wednesday 16 april picked up on market (free)"
   },
   {
      "id":"firstFriday",
      "value":3.95,
      "label":"friday 11 april shipping (€3.95)"
   }
]
1个回答

4
  <script type="text/x-handlebars" data-template-name="index">
    <ul>
    {{#each item in model}}
      <li>
        {{my-radio-button content=item action='setShippingCost'}}
        <label {{bind-attr for=item.id}}>{{item.label}}</label>
      </li>
    {{/each}}
    </ul>
  </script>

以下是JavaScript代码:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
       {
          "id":"tomorrow",
          "value":1,
          "label":"wednesday 16 april shipped on market day (€1)"
       },
       {
          "id":"marketPickup",
          "value":0,
          "label":"wednesday 16 april picked up on market (free)"
       },
       {
          "id":"firstFriday",
          "value":3.95,
          "label":"friday 11 april shipping (€3.95)"
       }
     ];
  }
});

App.IndexController = Ember.Controller.extend({
  choosenShippingCosts: '',
  actions: {
    setShippingCost: function(id){
      console.log('Selected shipping cost id: '+id);
      this.set('choosenShippingCosts', id);
    }
  }
});

App.MyRadioButtonComponent = Ember.Component.extend({
  tagName: 'input',
  type: 'radio',
  attributeBindings: ['myName:name', 'type', 'myValue:value'],
  willInsertElement: function(){
    this.setProperties({
      myName: 'shippinOptions',
      myValue: this.get('content.value')
    });
  },
  change: function(){
    this.sendAction('action', this.get('content.id'));
  }
});

以下是JSBin链接:


感谢您的回复并使用 JSBin 进行工作!非常好用! - DelphiLynx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接