I'm currently working on designing an angular directive for selecting items from a categorized list. Each item in the list should be selectable using a checkbox.
The input data that will be provided to the directive looks something like this:
[
{
"id": "1",
"name": "category1",
"items": [
{
"id": "1",
"name": "item1"
},
{
"id": "2",
"name": "item2"
},
{
"id": "3",
"name": "item3"
},
{
"id": "4",
"name": "item4"
}
]
},
{
"id": "2",
"name": "category2",
"items": [
{
"id": "5",
"name": "item5"
},
{
"id": "6",
"name": "item6"
}
]
}
]
Additionally, there is an object containing pre-checked items:
{
"1": [
"2",
"4"
]
}
This means that the items with id 2 and 4 from category 1 should already be checked when the view loads.
Currently, the code I have implemented results in this particular display:
https://i.stack.imgur.com/dOciF.jpg
To manage the checked state, I am utilizing the ng-checked
directive:
<input id="item-{{item.id}}" value="{{item.id}}" type="checkbox" ng-checked="isSelected(cat,item)">
When users check or uncheck an item, I need to update the selected items object to match the current selection. Is there a better way to structure this logic? How can I effectively handle this situation?
Please refer to my solution on Plunker: http://plnkr.co/edit/6fbfZnQCq5fq1zDp8VIB.