AngularJS ng-checked Directive Example
Hello readers, ng-checked in the angular library is a directive that reads the checked or unchecked status of the radio buttons and check-boxes. In this tutorial, we will see how this directive works in the angular library.
1. Introduction
AngularJS is a JavaScript MVC or Model-View-Controller framework developed by Google that lets developers build well structured, easily testable, and maintainable front-end applications. But before we start creating a real application using the angular library, let us see what the important parts of an angular application are.
1.1.1 Templates
In angular, a template is an HTML
with added markups. The angular library compiles the templates and renders the resultant HTML
page.
1.1.2 Directives
Directives are the markers (i.e. attributes) on a DOM element that tell angular to attach a specific behavior to that DOM element or even transform the DOM element and its children. Most of the directives in the angular library start with the ng
. The directives consist of the following parts:
ng-app
: Theng-app
directive is a starting point. If the angular framework finds theng-app
directive anywhere in theHTML
document, it bootstraps (i.e. initializes) itself and compiles theHTML
templateng-model
: Theng-model
directive binds anHTML
element to a property on the$scope
object. It also binds the values of angular application data to theHTML
input controlsng-bind
: Theng-bind
directive binds the angular application data to theHTML
tagsng-controller
: Theng-controller
directive specifies a controller in theHTML
element. This controller will add behavior or support the data in thatHTML
element and its child elementsng-repeat
: Theng-repeat
directive repeat a set ofHTML
elements for each item in a given collectionng-checked
: Theng-checked
directive reads the checked or unchecked status of the radio buttons and check-boxes. This directive sets the value as ‘true’ or ‘false’ and has a priority of value100
1.1.3 Expressions
An expression is like a JavaScript code usually wrapped inside the double curly braces such as {{ expression }}
. The angular library evaluates the expression and produces a result.
These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple example using the angular library.
2. AngularJS ng-checked Directive Example
Here is a step-by-step guide for implementing the ng-checked directive in the angular web applications.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the ‘Maven Web App’ Archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will enter the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>AngularJsNgCheckedEx</groupId> <artifactId>AngularJsNgCheckedEx</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
3. Application Building
Let’s start building an application to understand the basic building blocks of this tutorial in the angular library.
3.1 Load the Angular framework
Since it is a pure JavaScript framework, we should add its reference using the <script>
tag.
<script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
3.2 Define the Angular application
Next, we will define the angular application using the <ng-app>
and <ng-controller>
directives.
index.jsp
<div ng-app="myApp" ng-controller="myCtrl"> ... </div>
3.3 Define the Angular Controller
The JavaScript file i.e. controller.js
includes the myCtrl
function as the “controller” in the Model-View-Controller. This JavaScript code has the random employee details stored in an array format and the delete()
function that drops the selected employee records. Do note, the angular function will be executed on the $scope
objects through a button click.
controller.js
var mainApp = angular.module("myApp", []); mainApp.controller('myCtrl', ['$scope', function ($scope) { var arr = []; $scope.empList = [ { id: '101', fName: 'John', lName: 'Gordon' }, { id: '102', fName: 'Smith', lName: 'Bing' }, { id: '103', fName: 'Allen', lName: 'Ross' }, { id: '104', fName: 'Marry', lName: 'Potter' }, { id: '105', fName: 'Jennifer', lName: 'White' } ]; $scope.getIndex = function (id, isTrue) { if (isTrue) { arr.push(id); } else { var index = arr.indexOf(id); arr.splice(index, 1); } }; $scope.delete = function (isMaster) { if (isMaster) { $scope.empList = []; } else { for (var i = 0; i < arr.length; i++) { var rec = $scope.empList.filter(function (p) { return p.id == arr[i] }); var idx = $scope.empList.indexOf(rec[0]); $scope.empList.splice(idx, 1); } }; arr = []; }; }]);
3.4 Complete Application
In this example, we have an employee table with a check-box for each employee record. On a button click, the record will be dropped for the selected (i.e. checked) check-box. Also, there is a master check-box for selecting all records and dropping them at once. Complete the above steps to understand the usage.
index.jsp
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>AngularJS ng-Checked Directive Example</title> <!-- AngularJs Javascript File --> <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script> <script type="text/javascript" src="resource/js/controller.js"></script> <!-- Bootstrap Css --> <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" href="resource/css/controller.css"> </head> <body> <div id="angularCheckedExample" class="container"> <h1 align="center" class="text-primary">AngularJS - ng-Checked Directive Example</h1> <hr /> <!------ ANGULAR JAVASCRIPT 'ng-Directive' EXAMPLE ------> <div ng-app="myApp" ng-controller="myCtrl"> <div class="container"> <div class="input-group"> <label>Delete all: </label><input id="delMasterCheckBox" type="checkbox" ng-model="masterCheckBox" /> <sup class="text-info position">Click "Delete all" to select all employees</sup> <!------ DELETE BUTTON ------> <div class="input-group-btn"> <button id="dBtn" type="button" class="btn btn-danger" ng-click="delete(masterCheckBox)">Delete</button> </div> </div> <!------ EMPLOYEE LIST ------> <div> </div> <table class="table table-hover pointer"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Action</th> </tr> </thead> <tbody> <tr ng-repeat="e in empList"> <td>{{ e.id }}</td> <td>{{ e.fName }}</td> <td>{{ e.lName }}</td> <td> <input id="delCheckBox" type="checkbox" ng-checked="masterCheckBox" ng-model="isTrue" ng-change="getIndex(e.id, isTrue)" /> </td> </tr> </tbody> </table> </div> </div> </div> </body> </html>
4. Run the Application
As we are ready for all the changes, let us compile the project and deploy the application on the tomcat server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.
5. Project Demo
Open your favorite browser and hit the following URL. The output page having the default employee list will be displayed.
http://localhost:8080/AngularJsNgCheckedEx/
Server name (localhost) and port (8080) may vary as per your Tomcat configuration.
Here we have the delete()
function attached to a button click. This angular function will drop the selected employee records as shown below.
That’s all for this post. Happy Learning!!
6. Conclusion
In this section, developers learned how to create a simple application using the ng-checked
directive. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of the ng-checked directive in the angular library.
You can download the full source code of this example here: AngularJsNgCheckedEx