Dynamically Create Inputs with Ember (and retrieve their values)

夙愿已清 提交于 2020-01-16 13:26:33

问题


I'm working with Ember.JS on the front-end and need to be able to create x number of input checkboxes depending on my model. Basically I want to do something like:

{{#each model}}
    {{input type="checkbox"}}
{{/each}}

While that works perfectly fine, I'm not sure how I can retrieve the values of x checkboxes from the controller upon submission. If it were just one, I might say:

{{input type="checkbox" checked=boxIsChecked}}

But I'm not sure how I can enumerate these inputs so that I might say:

{{input type="checkbox" checked=boxOneIsChecked}}

Ideally, I'd like to be able to be able to retrieve the checked values into an array. Is any of this possible? Or is there a superior solution I'm overlooking? Thanks!


回答1:


Each checkbox should be bound to something on the model (or the controller).

{{#each item in model itemController="thing"}} 
                 <!-- ^ this will look for a controller named ThingController -->
  <li>
    {{item.color}}
    {{input type="checkbox" checked=isChecked}}
                          <!--      ^ each Thing model should have an isChecked boolean
                                      or the ThingController can have it -->
  </li>
{{/each}}

Assuming you are using an ArrayController the checkboxes would be some boolean on each of the models for the ArrayController.

If you are using an ObjectController presumably that has an array of things and you can loop over each of those.

The value will automatically be bound to the state of the checkbox for each model. So as long as you have a handle on the models you can see the corresponding checks.

Here is an example using plain JS objects: http://jsbin.com/dubewuxa/4/edit?html,js,console,output

If you're using ember-data you'd say item.get('good') in the action from that example.




回答2:


You can use Em.computed.filterBy to get the selected object values.

App.ApplicationController = Ember.ArrayController.extend({
  content: [
      { name: "Michael" },
      { name: "Bala" },
      { name: "Velmurugan" },
      { name: "raja" }
  ],
  selectedContacts: Em.computed.filterBy('content','isSelected')
});

<script type="text/x-handlebars" id="application">
    <ul class="list-unstyled">
    {{#each content}}
        <li>
        <div class="checkbox">
            <label>
              {{input type="checkbox" checked=isSelected}} {{name}}
            </label>
          </div>
        </li>
    {{/each}}
    <ul>
    Selected Contacts:
   <ul>
    {{#each selectedContacts}}
        <li>  {{name}}</li>
    {{/each}}
    <ul>

 </script>

Here sample fiddle



来源:https://stackoverflow.com/questions/24191592/dynamically-create-inputs-with-ember-and-retrieve-their-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!