Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if checkbox is checked or not in Angular [duplicate]

How to check if checkbox is selected/checked in this Angular example? So when user select/check first check box I want to get true and when unselect/uncheck it I want false.

angular.module('app', [])
  .controller('Controller', function($scope) {
    $scope.toggleSelection = function toggleSelection() {
      // how to check if checkbox is selected or not

    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Controller">
  <h1>Get checkbox selection (true/false)</h1>
  <label>
    <input id="one" type="checkbox" ng-click="toggleSelection()">This
  </label>
  <br>
  <label>
    <input type="checkbox" ng-click="toggleSelection()">That
  </label>
  <br>
  <label>
    <input type="checkbox" ng-click="toggleSelection()">Lorem
  </label>
  <br>
  <label>
    <input type="checkbox" ng-click="toggleSelection()">Ipsum
  </label>
</div>
like image 527
akuljana Avatar asked Oct 13 '16 10:10

akuljana


2 Answers

It works:

angular.module('app', [])
      .controller('Controller', function($scope) {
        $scope.toggleSelection = function toggleSelection(event) {
          // how to check if checkbox is selected or not
          alert(event.target.checked);
        };
      })
<!DOCTYPE html>

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="Controller">
    <h1>Get checkbox selection (true/false)</h1>
    <label>
      <input type="checkbox" ng-click="toggleSelection($event)"> This
    </label>
    <br>
    <label>
      <input type="checkbox" ng-click="toggleSelection($event)"> That
    </label>
    <br>
    <label>
      <input type="checkbox" ng-click="toggleSelection($event)"> Lorem
    </label>
    <br>
    <label>
      <input type="checkbox" ng-click="toggleSelection($event)"> Ipsum
    </label>
  </div>
</body>

</html>
like image 85
Gaurav Srivastava Avatar answered Nov 06 '22 03:11

Gaurav Srivastava


I would suggest that you use ng-model instead.

<input type="checkbox" ng-model="checkbox1">

Then in your controller $scope.checkbox1 will be true or false based on if the checkbox is checked or not.

if($scope.checkbox1){
    //Checkbox is checked
} else {
    //Checkbox is not checked
}
like image 21
Amygdaloideum Avatar answered Nov 06 '22 03:11

Amygdaloideum