Search code examples
angularjscheckboxangularjs-ng-repeat

AngularJS: uncheck checkboxes with no ng-model attribute


I want to uncheck all checkboxes when press some button. I need to do this on AngularJS (no jQuery). My checkboxes don't have ng-model attribute. How I can uncheck them? My HTML structure:

    <li ng-repeat="channel in channelsList">
         <div class="checkbox">
             <label><input type="checkbox" value="" ng-click="isChecked(channel.id)">
                <img src="images/checkbox-unchecked.png" alt="" class="unchecked">
                <img src="images/checkbox.png" alt="" class="checked"><span>{{channel.name}}</span>
             </label>
         </div>
    </li>

My channelsList is only an array of objects with 2 properties: id and name.

Thanks for helping!


Solution

  • Bind checkbox ng-model to a _selected property. Please note that I use _selected and not selected in case your API would in a near future return a selected property that would collide with this one.

    index.html

    <!doctype html>
    
    <html lang="en" ng-app="app">
    <head>
      <meta charset="utf-8">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
      <script src="script.js"></script>
    </head>
    
    <body ng-controller="SampleController">
    
        <ul>
            <li ng-repeat="channel in channelsList">
                 <input type="checkbox" ng-model="channel._selected" /> {{channel.name}} (id={{channel.id}})
            </li>
        </ul>
        <button ng-click="uncheckAll()">Uncheck all</button>
    
    </body>
    </html>
    

    script.js

    angular.module('app', []);
    
    angular.module('app').controller('SampleController', function ($scope) {
    
        $scope.channelsList = [
         {id: 'c1', name: 'CNN'}, 
         {id: 'c2', name: 'BBC'},
         {id: 'c3', name: 'Discovery Channel'}
        ];
    
        $scope.uncheckAll = function() {
            angular.forEach($scope.channelsList, function (channel) {
                channel._selected = false;
            });
        };
    });
    

    Here is the plunker : http://plnkr.co/edit/VPOjKMUVyrMpPfT9jLz3