Skip to content

Instantly share code, notes, and snippets.

@farisj
Created July 25, 2017 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save farisj/651b176978236c678e9833afafea4327 to your computer and use it in GitHub Desktop.
Save farisj/651b176978236c678e9833afafea4327 to your computer and use it in GitHub Desktop.
Indeterminate/Checked Inputs in Ember
import Ember from 'ember';
import _ from "lodash";
const { computed, get, set } = Ember;
export default Ember.Component.extend({
items: [],
allItems: computed.alias('items'),
selectedItems: [],
allItemsSelected: computed('allItems.length', 'selectedItems.length', function(){
return get(this, 'allItems').length === get(this, 'selectedItems').length;
}),
someItemsSelected: computed('allItems.length', 'selectedItems.length', function(){
return get(this, 'selectedItems').length > 0;
}),
actions: {
toggleAllItems: function(){
if (get(this, 'someItemsSelected')){
set(this, 'selectedItems', []);
} else {
set(this, 'selectedItems', get(this, 'allItems'));
}
},
selectItem: function(item){
let selectedItems = get(this, 'selectedItems').toArray();
if (selectedItems.includes(item)) {
set(this, 'selectedItems', _.without(selectedItems, item));
} else {
set(this, 'selectedItems', _.union(selectedItems, [item]));
}
}
},
});
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
items: [ {name: 'milk'}, {name: 'eggs'}, {name: 'cheese'} ]
});
<h1>My Grocery List</h1>
<br>
{{my-component items=items}}
<br>
<br>
To recreate this bug:
<ul>
<li> Select one or more items </li>
<li> Uncheck them - note that the total count and checkbox reset correctly to 0</li>
<li> Select one or more items (not all three) and note 'allItemsSelected' is false </li>
<li> Check the indeterminate checkbox to unselect all items</li>
<li> Note that even though 'allItemsSelected' is false, the checkbox is selected</li>
</ul>
<input
type="checkbox"
checked={{allItemsSelected}}
indeterminate={{someItemsSelected}}
onchange={{action "toggleAllItems"}}>
{{selectedItems.length}} of {{allItems.length}}
( allItemsSelected == {{allItemsSelected}})
<br>
{{#each items as |item|}}
<div>
<input
type="checkbox"
checked={{contains item selectedItems}}
onchange={{action "selectItem" item}}>
{{item.name}}
</div>
<br>
{{/each}}
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1",
"ember-composable-helpers": "1.1.3",
"ember-lodash": "4.17.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment