How to Create a Checkbox List in AngularJS

Muhammad Adil Feb 02, 2024
How to Create a Checkbox List in AngularJS

This tutorial will demonstrate creating a simple checkbox list in AngularJS. We will use the ng-repeat directive to iterate over an array of objects containing a property called selected.

We will also use the ng-model to bind the selected property of each object in the array to a checkbox input.

Steps to Create an Angular Checkbox List

The following steps will guide you create an Angular checkbox list.

  • Create a new AngularJS project.
  • Add data to controller.
  • Add list items to the controller and add ng-repeat directive.
  • Add checkbox list to HTML file and add ng-model directive.
  • Create a function that will loop through the items in a controller and check if they are checked or not, then show or hide them accordingly.

Let’s discuss an example that will help us create an Angular checkbox list.

We need to set up a development environment to start building Angular apps. For this, we will install NodeJS and the Angular CLI tool globally on our system.

To do this, run the following command.

$ng new angular-checkbox-list-app

After this, let’s write the JavaScript and HTML codes.

JavaScript code:

angular.module('sam', ['checklist-model'])
    .controller('demo', function($scope) {
        $scope.countryList = [
            { name: 'America'},
            { name: 'England'},
            { name: 'Canada'},
            { name: 'Scotland'}
        ];
        $scope.selected = {
            country: []
        };
    });

HTML code:

<div ng-app="sam">
    <div ng-controller="demo">
    <h2>
    Example of Angular Checkbox List
    </h2>
        <label ng-repeat="country in countryList"><input type="checkbox" checklist-model="selected.country" checklist-value="country" /> {{country.name}}<br/> </label>
        <br/>
        <p>
        Selection will show here
        </p>
        {{selected.country}}
	</div>
</div>

Output:

Angular Simple Checkbox list

In this example, we wrote a list of some countries and mainly used ng-repeat. It’s used to display the data in the table, list, or another UI component.

Moreover, it is easy to use, intuitive and provides many customizations. Lastly, in the Angular checkbox list, you can easily add or remove items without breaking the whole code; it makes a list flexible for your needs.

Click here to check the live demonstration of the code above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - Angular List