How to Create a Checkbox List in AngularJS

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.

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.

TypeScript
 typescriptCopy$ng new angular-checkbox-list-app

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

JavaScript code:

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

HTML code:

HTML
 htmlCopy<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.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
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