1

How do you make a parent div click propagate to its child checkbox in AngularJS? The Checkbox will have the hidden attribute, so we need to allow the parent div be the clickable entity.

HTML:

  <body ng-app="checkboxApp">
    <div ng-controller="MainController">
      <h1>Hello Plunker!</h1>
      <form name="myForm">
        Value1:<input type="checkbox" ng-model="value1" /><br />
        Value2:<input type="checkbox" value="value-2" ng-model="value2" ng-true-value="YES" ng-false-value="NO" /><br />
        <tt>value1 = {{value1}}</tt><br />
        <tt>value2 = {{value2}}</tt><br />

        <hr />

        <div class="btn btn-primary">
          Value1 (hidden):<input type="checkbox" ng-model="value1" hidden/><br />
        </div>
        <div class="btn btn-primary" >
          Value2:<input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO" /><br />
        </div>
      </form>
    </div>
  </body>

JS:

angular.module('checkboxApp', []);

angular.module('checkboxApp')
  .controller('MainController', [ '$scope', function MainController($scope){
    $scope.value1 = true;
    $scope.value2 = 'YES'
  }]);

Plnkr: here

I have tried a click function() as well on the ng-change, but I still can't get it working.

1 Answer 1

2

All you need to do is add an ng-click onto the parent div like this. This example would work if you did not use ng-true-value and ng-false-value.

<div class="btn btn-primary" ng-click="value1 = !value1>
  Value1 (hidden):<input type="checkbox" ng-model="value1" hidden/><br />
</div>
<div class="btn btn-primary" ng-click="value2 = !value2>
  Value2:<input type="checkbox" ng-model="value2"/><br />
</div>

Otherwise just use a function: ng-click="toggle(value2)"

$scope.toggle = function(val) {
    if (val === "YES") {
        val = "NO";
    } else {
        val = "YES";
    }
}

Here is a Plunker

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

2 Comments

hrm... I tried that earlier and it said that I needed a ng-model.... can't get it to reproduce it, so maybe I had a syntax error when I tried moving the click to the parent div.
@Zack Argyle, this has an issue with when the user click the checkbox itself. That'll trigger a click on the parent div, and the checkbox value will remain the same.

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.