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 :)

3
  • Don't you have a Controller for this app? Can you show us your Javascript code - your controller? Commented Oct 3, 2016 at 22:31
  • I do have an empty controller, I was wondering if this was possible purely through directive computation, don't need the data to go anywhere Commented Oct 3, 2016 at 22:32
  • I'd suggest you try using the Controller. Commented Oct 3, 2016 at 22:39

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

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.
What I need is for the initial value to be 100 and on checkbox click, the value toggles to 150
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.

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.