父div的ng-click子复选框

时间:2014-06-28 06:13:15

标签: javascript angularjs angularjs-ng-click angularjs-ng-change

如何让父div点击传播到AngularJS中的子复选框?复选框将具有hidden属性,因此我们需要允许父div成为可单击的实体。

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

我在ng-change上尝试过点击功能(),但我仍然无法正常工作。

1 个答案:

答案 0 :(得分:2)

您需要做的就是像这样在父div上添加ng-click。如果您不使用ng-true-value和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>

否则只需使用一个函数:ng-click =“toggle(value2)”

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

这是Plunker