0

I'm trying to create an angular directive making me able to select from a list of items group by category. Each item should be selectable using a checkbox.

The input data to the directive is something like

[
  {
    "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"
      }
    ]
  }
]

And the object of pre-checked items is:

{
  "1": [
    "2",
    "4"
  ]
}

Here item with id 2 and 4 from category with 1 should be pre-checked.

My code results in this view:

select box

The checked-state is handled using the ng-checked directive:

<input id="item-{{item.id}}" value="{{item.id}}" type="checkbox" ng-checked="isSelected(cat,item)">

When checking/unchecking an item, the selected items object should be updated to reflect the current state. How can I handle this? Should all this be structured in a different way?

See my plumber: http://plnkr.co/edit/6fbfZnQCq5fq1zDp8VIB.

1 Answer 1

1

As always, there is multiple ways to achieve this. My suggestion:

Use ng-model on your inputs:

<input ng-model="selected[cat.id][item.id]" 
       id="item-{{item.id}}" 
       value="{{item.id}}" 
       type="checkbox" 
       ng-checked="selected[cat.id][item.id]">

This will require a slight modification of your selectedItems property (it is now an object instead of an array):

$scope.selectedItems = {
    "1": {
        "2": true,
        "4": true
    }
};

The ng-checked in the HTML will automatically check the items which are marked true.

I'm not sure how you want to handle the selection of categories, but I hope this will give you an idea!

Check the updated Plunker.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.