Search code examples
ember.jsnsarraycontrollercomputed-properties

ArrayController's property for each item in the model in ember


I've an Array controller which has the property "isChecked" (boolean property). In my controller I want to get the collection of elements which are "checked" (I mean selected). I'm not sure how to access the controller's property in the model.

My controller is as follows:

App.ExampleController = Ember.ArrayController.extend({
    isChecked: false,
    totalElements: function()
    {
        return this.model.get('length');
    }.property('@each'),
    selectedElements: function()
    {
        var content = this.get('content');
        console.log(content.filterBy('isChecked'));
        return content.filterBy('isChecked');
    }.property('isChecked'),
});

I linked the "isChecked" property to a checkbox inside each helper as follows..

<ul>
   {{#each model}}
        <li>
            {{input type="checkbox" checked=isChecked}}
            {{name}}
        </li>
    {{/each}}
</ul>

I will display all the items in the model with a checkbox associated with it. The user can select few items from it. So I want those items.

enter image description here

Now I want to get the list of elements which are "checked". Either as a computed property or under any action.

Thank you.


Solution

  • I think you need to move the isChecked property onto an ObjectController, then reference that controller in the array controller with the itemController property.

    Array Controller:

    App.IndexController = Ember.ArrayController.extend({
      itemController: 'color',
    
      totalElements: function() {
        return this.get('length');
      }.property('[]'),
    
      selectedElements: Ember.computed.filterBy('@this', 'isChecked', true)
    });
    

    (The @this means that the computed property will reference the array of item controllers.)

    Item Controller:

    App.ColorController = Ember.ObjectController.extend({
      isChecked: false
    });
    

    http://emberjs.jsbin.com/tazojejuwi/1/edit

    Hope that helps.