jthomasbailey
jthomasbailey

Reputation: 410

How to calculate a value using checkboxes and Angular?

I'm trying to do something like this:

<form name="myForm" ng-controller="Ctrl">
      Value1: <input type="checkbox" ng-number="100"> <br/>
      Value2: <input type="checkbox" ng-number="250"

      add 5% to the total sum of the checked boxes: <input type="checkbox" ng-percent=".05"
     <br/>

     total value = {{how do you do this?}}
 </form>

So if Value1 is checked the total value is "100", if both values are checked then "350", or if the "add 5%" is also checked then: total value = ({{total sum}} + ({{total sum}} * .05))

I can do this with jQuery but I'm having trouble wrapping my head around how to do it the 'Angular' way.

Upvotes: 0

Views: 2077

Answers (1)

musically_ut
musically_ut

Reputation: 34288

I think this is what you are looking for: http://plnkr.co/edit/WNsjwMuBw2kDBaR7PLRy?p=preview

You need to make a two-way bind between the input elements and some boolean values on the $scope using ng-model:

  <div><label><input type="checkbox" ng-model="opts.val1" /> Value 1</label></div>
  <div><label><input type="checkbox" ng-model="opts.val2" /> Value 2</label></div>
  <div><label>add 5% to the total sum of the checked boxes: <input type="checkbox" ng-model="opts.val3" /></label></div>

And in the controller:

$scope.opts = {
 val1: false,
 val2: false,
 val3: false
};

Then you can expose the total value as a function on the $scope and bind it, as you have suggested, to the HTML using {{...}}:

  <label>Total: {{ computedTotal() }}</label>

And in the controller:

$scope.computedTotal = function () {
  // You can make the values configurable as well by exposing them on the $scope
  // and binding them to input tags using ng-model
  var opts = $scope.opts;
  var total = (opts.val1 ? 100 : 0) + (opts.val2 ? 250 : 0);
  var perc = opts.val3 ? 1.05 : 1;
   return perc * total;
};

Upvotes: 1

Related Questions