Angular.js

AngularJS Drag and Drop Example

Hello readers, in this tutorial, we will understand how to carry out the drag-and-drop feature in the angular web application. In this step-by-step approach, we’ll cover how to:

  • Bind the product catalog to the angular controller
  • Select an item in the product catalog and drag it to the shopping cart part
  • Drop the item in the shopping cart part and bind it with the angular expression

1. Introduction

Before we begin with the tutorial, let’s take a look at the Angular JavaScript and its characteristics.

1.1 Angular JavaScript

Angular 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: The ng-app directive is a starting point. If the angular framework finds the ng-app directive anywhere in the HTML document, it bootstraps (i.e. initializes) itself and compiles the HTML template
  • ng-model: The ng-model directive binds an HTML element to a property on the $scope object. It also binds the values of angular application data to the HTML input controls
  • ng-bind: The ng-bind directive binds the angular application data to the HTML tags

1.1.3 Expressions

An expression is like a JavaScript code usually wrapped inside the double curly braces such as {{ expression }}. Angular library evaluates the expression and produces a result.

1.2 Drag and Drop for Angular

Drag-and-Drop is a very common feature as it let users grab an object and drag it to a different place. Implementing this functionality in the angular library is easier with the jQuery Draggable and Droppable components. Developers can read this link to briefly study about the different options available with the draggable and droppable parts.

Fig. 1: Drag and Drop feature in Angular
Fig. 1: Drag and Drop feature in Angular

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 to show the drag-and-drop feature in the angular library.

2. AngularJS Drag and Drop Example

Here is a step-by-step guide for implementing the drag-and-drop example 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!

Fig. 2: Application Project Structure
Fig. 2: Application Project Structure

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.

Fig. 3: Create Maven Project
Fig. 3: Create 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.

Fig. 4: Project Details
Fig. 4: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 5: Archetype Selection
Fig. 5: Archetype Selection

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.

Fig. 6: Archetype Parameters
Fig. 6: Archetype Parameters

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>AngularDragdropEx</groupId>
	<artifactId>AngularDragdropEx</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 the drag-and-drop feature 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 Create the Angular controller

The dragdrop.js javascript file initializes the item’s list and binds the list to the ng-repeat tag. This angular directive generates the item’s list in the HTML list element.

dragdrop.js

$(function() {
	$("#product_catalog").accordion();
});

var app = angular.module('myApp', ['ngDragDrop']);

app.controller('myCtrl', function($scope, $timeout) {
	$scope.shirts = [{'title': 'Sweatshirt'}, {'title': 'Polo shirt'}, {'title': 'V-neck Shirt'}, {'title': 'U-neck Shirt'}];
	$scope.bag = [ {'title': 'Casual Day Bag'}, {'title': 'Medium-sized Shoulder Bag'}, {'title': 'Cross-body Bag'} ];
	$scope.gadget = [ {'title': 'Apple iPad'}, {'title': 'Cannon DSLR'}, {'title': 'Samsung Phone'}, {'title': 'Apple iPhone'} ];
	$scope.shopBagList = [];

	$scope.hideMe = function() {
		return $scope.shopBagList.length > 0;
	}
});

3.4 Bind the Model

In this step, we are using the <ng-repeat> directive to display the shirts, bag, gadget, and shopping cart items list.

index.jsp

<!-- T-shirts Item List -->
<ul>
	<li class="pointer" ng-repeat='item in shirts' ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="shirts" jqyoui-draggable="{index: {{$index}}, animate: true, placeholder: 'keep'}">{{ item.title }}</li>
</ul>

<!-- Bags Item List -->
<ul>
	<li class="pointer" ng-repeat='item in bag' ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="bag" jqyoui-draggable="{index: {{$index}}, placeholder: 'keep'}">{{ item.title }}</li>
</ul>

<!-- Gadgets Item List -->				 
<ul>
	<li class="pointer" ng-repeat='item in gadget' ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="gadget" jqyoui-draggable="{index: {{$index}}, placeholder: 'keep'}">{{ item.title }}</li>
</ul>

<!-- Shopping Cart Items List -->
<ol data-drop="true" ng-model='shopBagList' jqyoui-droppable="{multiple:true}">
    <li ng-repeat="item in shopBagList track by $index" ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="shopBagList" jqyoui-draggable="{index: {{$index}},animate:true}">{{ item.title }}</li>
    <li class="placeholder" ng-hide="hideMe()">Add your items here</li>
</ol>

3.5 Complete Application

Complete the above steps to show the front view and understand the use of the drag-and-drop feature in an angular web application. The important point to note is that we have introduced the angular-dragdrop.min.js to carry out the drag-and-drop feature.

index.jsp

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>AngularJS Drag-and-Drop</title>
      
      <!-- jQuery Files -->
      <script type="text/javascript" src="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9hamF4Lmdvb2dsZWFwaXMuY29tL2FqYXgvlibs/jquery/1/jquery.min.js"></script>
      <script type="text/javascript" src="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9hamF4Lmdvb2dsZWFwaXMuY29tL2FqYXgvlibs/jqueryui/1/jquery-ui.min.js"></script>
      
      <!-- AngularJs Files -->
      <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
      <script type="text/javascript" src="resource/js/dragdrop.js"></script>
      
      <!-- Angular Drag-and-Drop Js -->
      <script type="text/javascript" src="resource/js/angular-dragdrop.min.js"></script>
      
      <!-- Bootstrap File -->
      <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
      <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9hamF4Lmdvb2dsZWFwaXMuY29tL2FqYXgvlibs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.min.css">
      <link rel="stylesheet" href="resource/css/angular-dragdrop.min.css">
   </head>
   <body>
      <div id="angularDragdrop" class="container">
         <h1 align="center" class="text-primary">AngularJS Drag-and-Drop</h1>
         <hr />
         
         <!------ ANGULAR JAVASCRIPT 'DRAG-AND-DROP' EXAMPLE ------>
         <div ng-app="myApp" ng-controller="myCtrl">
            <div id="products">
               <h3 align="center" class="text-danger">Products</h3>
               <div id="product_catalog">
                  <h4><a href="#" class="text-secondary">T-Shirts</a></h4>
                  <div>
                     <ul>
                        <li class="pointer" ng-repeat='item in shirts' ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="shirts" jqyoui-draggable="{index: {{$index}}, animate: true, placeholder: 'keep'}">{{ item.title }}</li>
                     </ul>
                  </div>
                  <h4><a href="#" class="text-secondary">Bags</a></h4>
                  <div>
                     <ul>
                        <li class="pointer" ng-repeat='item in bag' ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="bag" jqyoui-draggable="{index: {{$index}}, placeholder: 'keep'}">{{ item.title }}</li>
                     </ul>
                  </div>
                  <h4><a href="#" class="text-secondary">Gadgets</a></h4>
                  <div>
                     <ul>
                        <li class="pointer" ng-repeat='item in gadget' ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="gadget" jqyoui-draggable="{index: {{$index}}, placeholder: 'keep'}">{{ item.title }}</li>
                     </ul>
                  </div>
               </div>
            </div>
            <div id="cart">
               <h3 align="center" class="text-danger">Shopping Cart</h3>
               <div class="ui-widget-content">
                  <ol data-drop="true" ng-model='shopBagList' jqyoui-droppable="{multiple:true}">
                     <li ng-repeat="item in shopBagList track by $index" ng-show="item.title" data-drag="true" data-jqyoui-options="{revert: 'invalid', helper: 'clone'}" ng-model="shopBagList" jqyoui-draggable="{index: {{$index}},animate:true}">{{ item.title }}</li>
                     <li class="placeholder" ng-hide="hideMe()">Add your items here</li>
                  </ol>
               </div>
            </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.

Fig. 7: How to Deploy Application on Tomcat
Fig. 7: How to Deploy Application on Tomcat

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 will be displayed.

http://localhost:8080/AngularDragdropEx/

Server name (localhost) and port (8080) may vary as per your Tomcat configuration.

Fig. 8: Output page
Fig. 8: Output page

Users can now drag the item list from the product catalog and drop it to the shopping cart module as shown below.

Fig. 9: A drag-and-drop feature in an Angular application
Fig. 9: A drag-and-drop feature in an Angular application

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned the drag-and-drop feature in the angular library. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a tutorial of the drag-and-drop feature in the angular library.

Download
You can download the full source code of this example here: AngularDragdropEx

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button