Best way to get checkbox values


#1

If in my Controller, I have:

$scope.expense = {tags: []};
$scope.tags = ['Tag1', 'Tag2']

In my view I have:

<ul class="list">
  <li class="item item-checkbox" ng-repeat="tag in tags">
    <label class="checkbox">
      <input type="checkbox" ng-model="expense.tags[tag]">
    </label>
    {{tag}}
  </li>
</ul>

When I click the checkbox, it sets my model like so:

[Tag1: true, Tag2: true]

What I want is a flat array like:

[Tag1, Tag2]

Is there a better to get the values from the checkbox and set them in an array on the model?


#2

@steve what I usually do in this case is a tag to boolean map, like this:

$scope.tags = [{
  text: 'Tag text',
  enabled: false
}]
<checkbox ng-repeat="tag in tags" ng-model="tag.enabled">{{tag.text}}</checkbox>

Which will set the enabled field true or false as it’s toggled (untested).

Does that help? <checkbox> is the same as the expanded code above, just a little more compact for Angular.


#3

Yeah, I was hoping to bind tags directly in the expense model. Using your suggestion(and my previous post), I would need to loop through the tags array to see which ones were selected and then set them on the expense model. I.e. (using coffeescript)

expense.tags = []
for t in tags
   expense.tags.push(t[‘text’]) if t.enabled

Anyway, thanks for the input!


#4

Also, wouldn’t the HTML for your example be this:

<ul class="list">
  <li class="item item-checkbox" ng-repeat="tag in tags">
    <label class="checkbox">
      <input type="checkbox" ng-model="tag.enabled">
    </label>
    {{tag.text}}
  </li>
</ul>

#5

Ended up doing this:

###coffeescript

$scope.allTags = ['Important', 'Critical']

$scope.expense = 
  tags: ["Important"]

$scope.toggleTag = (tag) ->
  idx = $scope.expense.tags.indexOf(tag)
  if idx > -1
    $scope.expense.tags.splice(idx, 1)
  else
    $scope.expense.tags.push(tag)


<ul class="list">
  <li class="item item-checkbox" ng-repeat="tag in allTags">
    <label class="checkbox">
      <input type="checkbox" ng-checked="expense.tags.indexOf(tag) > -1" ng-click="toggleTag(tag)">
    </label>
    {{tag}}
  </li>

Thanks to: http://stackoverflow.com/questions/14514461/how-can-angularjs-bind-to-list-of-checkbox-values


#6

If you use the <checkbox> directive, you get all that markup for free, and it supports ng-model directly so you don’t have to write out all the item stuff. But you are free to use the raw markup if you like!


#7

Then the docs should provide that as a reference!

Edit: actually kinda weird, I just tried the <checkbox> syntax and it didn’t work. Oh well.