trigger
trigger

Reputation: 497

Angular How to check checkbox with click on div

I need to check/unchec checkbox with click on div "user check" and call doIfChecked(user).

I can check checkbox in ng-repeat and call doIfChecked.

var app = angular.module('app', []);

app.controller('cont', ['$scope', function($scope) {
  
$scope.users = {user1:1,user2:2,user3:3};
  
$scope.toggleUserCo = function(user) {
    user.co = !user.co;
}


$scope.doIfChecked = function (array) {

}

}]);
.user_check {
width: 600px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


        <div class="user_check" ng-app="app" ng-controller="cont" >
          
<div class="user_check" ng-app="app" ng-click="toggleUserCo()" ng-repeat="us in users">
    <input type="checkbox" checklist-value="contact" checklist-model="user.co" ng-click="doIfChecked(user)"/>
</div>

Upvotes: 0

Views: 2337

Answers (1)

Tom
Tom

Reputation: 7740

Assuming user.co is some boolean value and checklist-model is the equivalent to ng-model in whatever directive you're using, you can set the ng-click on the div to set user.co = !user.co

For example:

<div class="user_check" ng-app="app" ng-click="toggleUserCo()">
    <input type="checkbox" checklist-value="contact" checklist-model="user.co" ng-click="doIfChecked(user)"/>
</div>

And in your controller (or, based on the fact that I don't see you having a controller defined inside of the ng-app, I guess this would go wherever you're putting your logic (which should be a controller or service...)):

$scope.toggleUserCo = function() {
    $scope.user.co = !$scope.user.co;
}

Edit

Since this is in an ng-repeat, you can just pass the user object to the toggleUserCo function and perform the operation on that:

<div class="user_check" ng-app="app" ng-click="toggleUserCo(user)">

And

$scope.toggleUserCo = function(user) {
    user.co = !user.co;
}

Upvotes: 2

Related Questions