Select all and Deselect all checkboxes in angularjs

This tutorial will explain how to achieve check all and uncheck all checkbox using angularjs and listing all checked values in the page. Find the demo and download the source code at the end of the tutorial.

Let’s start our tutorial

Find the folder structure

Select all and Deselect all checkboxes in angularjs 1

Select all and Unselect all checkbox

Create index.html and include the below code

<html>
    <head>
        <title>Check and Uncheck in check box in angularjs</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
        <script src="js/controller.js"></script>
    </head>
    <body ng-app="appModule" ng-controller="mainController">
        <div ui-view></div>
    </body>
</html>

In above code you can find <div ui-view></div> and controller.js and include the angular dependency.

<div ui-view></div> will initiate the default page which is defined in controller.js.

In controller file include the below code

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

app.config(function($stateProvider){
    $stateProvider.state('home',{
        url:'/',
        templateUrl:'templates/mainPage.html'
    });
});

app.controller('mainController',['$scope','$state',function($scope,$state){
    $state.go("home");
    $scope.allOption = "All";
    var modelScope = {
            "checkboxModel" : "checkboxModel",
            "selectedItems" : "selectedItems"
        };
    $scope.data = ["checkBox1","checkBox2","checkBox3"];
    
    $scope.checkboxModel = [];
    $scope.selectedItems = [];
    
    $scope.onClickFn = function(val){
        if(val == $scope.allOption)
            resultsFnAll();
        else
            addorRemoveItems(val);
    };
    
    function addorRemoveItems(val){
        if($scope[modelScope.checkboxModel][val]){
            $scope[modelScope.selectedItems].push(val);
        }else if(!$scope[modelScope.checkboxModel][val]){
            $scope[modelScope.selectedItems].splice($scope[modelScope.selectedItems].indexOf(val), 1);
        };
            
        if($scope[modelScope.selectedItems].length >= ($scope.data.length))
            $scope[modelScope.checkboxModel][$scope.allOption] = true;
        else
            $scope[modelScope.checkboxModel][$scope.allOption] = false;
    };
    function resultsFnAll(){
        var allVal = $scope[modelScope.checkboxModel][$scope.allOption];
        if(allVal)
            $scope[modelScope.selectedItems] = angular.copy($scope.data);
        else
            $scope[modelScope.selectedItems] = [];
        
        for (property in $scope["data"]) {            
            $scope[modelScope.checkboxModel][$scope["data"][property]] = allVal;
        };
    };
}]);

Include the below code in mainPage.html

<div ng-controller="mainController">
    <ul class="list-group">
        <li><input type="checkbox" ng-change="onClickFn(allOption)" ng-model="checkboxModel[allOption]" checked="checked"> {{allOption}}</li>
        <li ng-repeat="item in data">
            <input type="checkbox" ng-change="onClickFn(item)" ng-model="checkboxModel[item]" checked="checked"> {{item}}
        </li>
    </ul>

    <h2>Selected Value</h2>
    <li ng-repeat="val in selectedItems">{{val}}</li>
</div>

Demo

W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

  1. JamesRaw Avatar

    Your comment is awaiting moderation.

    This resource features a lot of fascinating and useful information.
    On this platform, you can discover a wide range of subjects that expand knowledge.
    Visitors will appreciate the resources shared through this platform.
    All topics is thoughtfully designed, making it simple to use.
    The content are relevant and engaging.
    It’s possible to find information on many areas.
    If you want to find useful facts, this site has something for everyone.
    All in all, this site is a great source for information seekers.
    https://companysites.info/
    https://roborant.info/

  2. NathanBlape Avatar

    Your comment is awaiting moderation.

    This online platform offers a lot of captivating and informative information.
    Here, you can learn about different articles that help you learn new things.
    Visitors will value the resources shared here.
    All topics is easy to navigate, making it pleasant to use.
    The posts are relevant and engaging.
    It’s possible to find information on various fields.
    No matter if you seek educational content, this site has something for everyone.
    To sum up, this resource is a reliable place for those who love learning.
    https://rublevo.info/

  3. NathanBlape Avatar

    Your comment is awaiting moderation.

    На этом сайте представлено большое количество полезного контента.
    Пользователи отмечают, что ресурс помогает быстро находить нужные сведения.
    Контент постоянно пополняется, что делает сайт практичным для чтения.
    Многие считают, что навигация ресурса очень понятна и позволяет сэкономить время.
    Большое разнообразие тем делает ресурс полезным для широкой аудитории.
    Также отмечается, что материалы подготовлены качественно и понятны даже новичкам.
    Сайт помогает расширять знания благодаря детальным обзорам.
    Таким образом, этот ресурс можно назвать удобным местом для изучения важных тем для каждого посетителя.
    https://icolog.ru

Leave a Reply

Your email address will not be published. Required fields are marked *