RSKMR
RSKMR

Reputation: 1892

Angularjs + Check Checkbox clicked or not

I am using angularjs. I have sample list of json. I am display the list using ng-repeat and I have checkbox in html. I need to find user checkbox is clicked or not(not checked or not).

Here's a working example:

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

app.controller('MainCtrl', function($scope) {
  $scope.result = {};
  $scope.result.name = 'World';
  var data = '[ { "button": 1, "name": "Test-1", "checked" : 0 }, { "button": 2, "name": "Test-2", "checked" : 0 }, { "button": 3, "name": "Test-3", "checked" : 1 }, { "button": 4, "name": "Test-4", "checked" : 0 }, { "button": 5, "name": "Test-5", "checked" : 1 } ]';

  $scope.result.list = JSON.parse(data);
});
<script src="https://code.angularjs.org/1.4.9/angular.js"></script>

<div ng-app="MyApp" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>{{result.list.name}}
  <ul>
    <li ng-repeat="list in result.list">
      <input type="checkbox" ng-model="list.isChecked" ng-checked="list.checked == 1">- {{list.name}}</li>
  </ul>
</div>

Expected output:

Find user clicked the checkbox or not. If checkbox already checked (3 & 5). If user unchecked means I need to identify.

Alternatively, here's a Plunker.

Upvotes: 0

Views: 845

Answers (1)

hityagi
hityagi

Reputation: 5256

As far as I understood, You want to check if the checkbox was clicked by user or not. Check out the below code changes or on Plunker

This code adds, isClicked attribute to the check-boxes that were clicked. Also it stores the current value of check-boxes in checked attribute.

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

app.controller('MainCtrl', function($scope) {
  $scope.result = {};
  $scope.result.name = 'World';
  var data = '[ { "button": 1, "name": "Test-1", "checked" : 0 }, { "button": 2, "name": "Test-2", "checked" : 0 }, { "button": 3, "name": "Test-3", "checked" : 1 }, { "button": 4, "name": "Test-4", "checked" : 0 }, { "button": 5, "name": "Test-5", "checked" : 1 } ]';

  $scope.result.list = JSON.parse(data);
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
  <script src="app.js"></script>

</head>

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>{{result.list}}
  <ul>
    <li ng-repeat="list in result.list">
      <input type="checkbox" ng-model="list.checked" ng-click="list.isClicked = true" ng-true-value="1" ng-false-value="0">- {{list.name}}</li>
  </ul>
</body>

</html>

Upvotes: 1

Related Questions