0

I'm having a hell of a time here, probably because I'm very new to Angular and I don't quite grok everything yet.

First the scenario, then hopefully some code:

I have a button that fetches a JSON object from an API call. It becomes $scope.collectors.

$http.post('get', $scope.formData).success(function(data) {
    $scope.collectors = data.results;
...

Then I take that and make a big list of these items with checkboxes, so you can pick and choose which ones you want to work with. When you've selected the ones you want, you click another button to collect all of these together and bulk operate on them.

So that's the overall story. They task I'm having trouble with is twofold. First, I'm simply trying to count the number of items that are checked. I've done it like this:

JS:
    $scope.selectedCollectors = {};

HTML:
    <div ng-repeat="collector in collectors">
        <input type="checkbox" name="collector-id" 
               value="{{collector.id}}"
               ng-model="selectedCollectors[collector.id]">
    </div>
    <p>Debug: {{ selectedCollectors }}</p>
    <p>There are {{ selectedCollectors.length }} items checked</p>

When I select items, the output of selectedCollectors is as expected:

{"8596784":true,"7458347":true}

But {{ selectedCollectors.length }} never increments or shows anything at all.

The second thing is basically what I'm trying to do is get the subset of the original JSON object to work with, based on the users selection. Other than looping through each item in $scope.collectors and comparing the ID to the IDs in selectedCollectors, is there a better more Angular-ish way to get this subset?

Something makes me feel like I should take this JSON object and turn it into a pure array, but maybe not...

Any advice or help is appreciated.

Spanky
  • 5,608
  • 10
  • 39
  • 45

1 Answers1

1

Here is my solution. http://jsfiddle.net/wittwerj/962wm/

First, I let angular add a "selected" property to the checked collector objects:
<div ng-repeat="collector in collectors">
<input type="checkbox" name="collector-id" value="{{collector.id}}"
ng-model="collector.selected" />
</div>

Then a second ng-repeat creates a filtered subset of selected collectors (see this question):
<div ng-repeat="collector in (selectedCollectors = (collectors | filter:{selected: true}))">

Note that the second ng-repeat is not generating any markup - just the selectedCollectors array, which can be accessed like a scope variable.

Community
  • 1
  • 1
j.wittwer
  • 9,497
  • 3
  • 30
  • 32