在Ember.js中处理多个复选框数组

时间:2014-04-10 14:06:39

标签: ember.js

我的表格中有多个复选框,它们具有相同的名称属性“classifications []”

代码:

<input type="checkbox" name="classification[]" value="Value 1" />
<input type="checkbox" name="classification[]" value="Value 2" />
<input type="checkbox" name="classification[]" value="Value 3" />

默认情况下它可以正常发布,就像这样发布“分类[]”

[ 0 => "Value 1", 1 => "Value 2"]

但是我希望这个在ember app中工作,所以我做了这个(缩短版本)

// index.html
{{input type="checkbox" name="classification[]" value="Cell Member" checked=classification}}

App.ApplicationController = Ember.Controller.extend({
  var user = this.store.createRecord('user',{
  classification: this.get("classification")
})
  user.save();
})

App.User = DS.Model.extend({
 classification: DS.attr("string")
});

但唯一发布的分类值为True ..

1 个答案:

答案 0 :(得分:3)

试试这个

// index.html
{{#for possibleValues}}
    <label>{{this.label}}</label>
    {{input type="checkbox" value=this.isChecked}}
{{/for}}
<a {{action save}}>save</a>

var possibleValue = [{
    label: 'Label for value 1',
    isChecked: false,
    value: 'Value 1'
  },{
    label: 'Label for value 2',
    isChecked: false,
    value: 'Value 2'
  },{
    label: 'Label for value 3',
    isChecked: false,
    value: 'Value 3'
  }];

App = Ember.Application.create();
App.ApplicationAdapter = DS.RESTAdapter.extend();
App.ApplicationController = Ember.ObjectController.extend({
  init: function () {
    this._super();
    var user = this.store.createRecord('user');
    this.set('content', user);
  },
  actions:{
    save: function () {
      var user = this.get('content'),
          collected = user.get('classifications');
      this.set('collected', collected);
      user.save();

     }
  },
  //executes when isChecked is changed in one item of possibleValues
  collectChecked: function () {
    var classifications;
    classifications = this.get('possibleValues').filterBy('isChecked', true); //filter checked only 
    classifications = classifications.mapBy('value'); //map values
    this.set('classifications', classifications);
    console.log(classifications);
  }.observes('possibleValues.@each.isChecked'),
  possibleValues: possibleValues
});

App.RawTransform = DS.Transform.extend({
  deserialize: function(serialized) {
    return serialized;
  },
  serialize: function(deserialized) {
    return deserialized;
  }
});

App.User = DS.Model.extend({
  classifications: DS.attr('raw')
});

http://jsbin.com/dokiwati/6/edit