0

I have a bound data variable named 'bool' which has a value of 100. When I click a checkbox I'd like the value to increase by adding 50 to it. What am I doing wrong?

<div ng-app="app">
  <h3 ng-model="bool = 100">BOOL</h3>
    <input type="checkbox" ng-model="add = 50"/>
    <div>{{bool + add}}</div>
</div>

Any help would be greatly appreciated,

Thank you :)

Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
meow-meow-meow
  • 508
  • 2
  • 10
  • 26

1 Answers1

1

ng-model cannot be an expression. If you need to assign a default value you should use ng-init.

Also, a checkbox has a value of either true (1) or false (0). So although {{bool + add}} will initially display 150, as soon as you check or uncheck the checkbox it will display either 100 or 101 because now add is either 0 or 1 depending on the checked state.

angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <div ng-app="app">
      <h3 ng-model="bool" ng-init="bool = 100; additional = 0">BOOL</h3>
        <input type="checkbox" ng-model="add" ng-change="additional = add * 50"/>
        <div>{{bool + additional}}</div>
    </div>
Lex
  • 6,758
  • 2
  • 27
  • 42
  • Hi @Lex, yep I tried that. What it does is initialize the value to 150, then on checkbox click sets it 101 (true having a value of 1) and on toggle switches between 100 and 101. – meow-meow-meow Oct 03 '16 at 22:42
  • What I need is for the initial value to be 100 and on checkbox click, the value toggles to 150 – meow-meow-meow Oct 03 '16 at 22:43
  • I'm not sure why you want to do this in the HTML, but I have updated my answer to show one possible approach. As suggested by ishmaelMakitla, though, this type of logic really belongs in the controller. – Lex Oct 03 '16 at 22:46