0

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.

3
  • What should ng-number and ng-percent do? Commented Nov 3, 2013 at 17:36
  • just to tell it how much to add when it's checked, not sure if that's how it should be done though Commented Nov 3, 2013 at 17:47
  • I think setting those values in the templates is a bad idea (TM). Instead, the values should be put in a model or, at least, in the controller and then edited via the template, if the need be. Commented Nov 3, 2013 at 17:57

1 Answer 1

1

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;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.