JavaScript and JQuery Essentials Trainin... (44 Blogs) Become a Certified Professional

How to perform CRUD operations in angularjs?

Published on Aug 22,2019 84 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Hey there, if you are looking to learn about CRUD Operations in AngularJS, then this is the right place for you. This article will walk you through CRUD operations in AngularJS and will explain how to use them.

The following topics will be covered in the article

So let’s begin. 

What is AngularJS?
AngularJS is an open-source front end development framework that implements the Model-View-Control architecture. AngularJS is based on TypeScript which is a superset of JavaScript. It is developed and maintained by Google. It is arguably one of the most popular frameworks available today, mainly because it enjoys sheer support from Google and incorporates the latest market trends. AngularJS is mostly used to develop single-page applications.

Features of AngularJS

  1. MVC – This framework is based on the widely used concept of MVC (Model-View-Control). This design pattern is being used in almost all modern-day web applications. MVC is based on segregating the business logic layer, the data layer, and the presentation layer into separate sections. This reduces confusion and helps in managing each section separately.
  2. Data Model Binding – There is no need to write specific code to bind data to HTML controls. This can be achieved by AngularJS by adding just a few snippets of code.
  3. Writing less code – Earlier, for DOM manipulation, a lot of JavaScript was required to be written to design any application. But with AngularJS, very less amount of code is needed for DOM manipulation.
  4. Unit testing ready – Along with AngularJS, the developers of Google also developed a testing framework named “Karma” which helps in designing unit tests for AngularJS applications.

What is Crud Operations?

CRUD basically stands for Create Read Update Delete data from server or Database.

How to Implement CRUD operations in AngularJS?

In this tutorial, we will learn to create a demo project for a student management portal which will allow the user to Create, Read(View), Edit(Update) and Delete data using AngularJS. There are so many editors in the market today which can be used for angular development e.g Webstorm, Aptana, Sublime Text, Eclipse IDE, etc. You can use any one of them. 

Basic Terms to be known in this tutorial:

  • Controller: This is a regular javascript object which is used to control the data of the AngularJS application.
  • Scope: It is the Binding part between the view and the controller. It is an object with defined properties and methods.

Let’s start coding.

STEP1: Create a student.html File :

student.html:

  • Add the below script inside the <head> tag of the html file. It is the CDN link that will help to get started with Angular.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

  • Create a angularCrud.js file in the same folder and reference the it with the script tag:

<script src="angularCrud.js"></script>

  • Create a Form to Register students.
<div ng-app="myapp" ng-controller="myctrl"> 
<!--ng-app directive is used to initialize an angular application -->
        <label>Name</label>

        <input type="text" name="name" ng-model="newStudent.name"/>

        <label>Address</label>

        <input type="text" name="address" ng-model="newStudent.address"/>

        <label>Dept.</label>

        <input type="text" name="dept" ng-model="newStudent.dept"/>

        <br/>

        <input type="hidden" ng-model="newStudent.id" />

        <input type="button" value="Save" ng-click="saveRecord()" class="btn btn-primary"/>

Note: Here on clicking the button we are calling saveRecord() function which we will create in angularCrud.js file where controller is defined.

  • Create a Table which will display the Data of the students along with options to update and delete students.
<table border="1" bordercolor="blue">

            <tr style="color:blue">

                <th style="width:150px">Name</th>

                <th style="width:150px">Address</th>

                <th style="width:150px">Dept</th>

                    <th>Action</th>

            </tr>

            <tr style="color:pink" ng-repeat="student in students">

                <td>{{ student.name }}</td>

                <td>{{ student.address }}</td>

                <td>{{ student.dept }}</td>

                <td>


                    <a  href="#" ng-click="edit(student.id)">edit</a> | 

                    <a href="#" ng-click="delete(student.id)">delete</a>

                </td>

            </tr>

        </table>

Note:-In the first Row we have added one more heading, “Action”. In the second row, we have added one more column in which two Anchors are used.

The first Anchor link is for the “Edit” function and the second Anchor link is for the “Delete” function. The Id of the Student is passed depending on the Anchors, in other words wherever the Anchors are placed, simultaneous to that, the Ids will be passed to the function.

  • Now our View Model e.g students.html is updated and its code is like this:
<!DOCTYPE html>
<html>
<head>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="angularCrud.js"></script>
<title>Student Management Portal</title>


</head>
<body>

<div ng-app="myapp" ng-controller="myctrl">

        <label>Name</label>

        <input type="text" name="name" ng-model="newStudent.name"/>

        <label>Address</label>

        <input type="text" name="address" ng-model="newStudent.address"/>

        <label>Dept.</label>

        <input type="text" name="dept" ng-model="newStudent.dept"/>

        <br/>

        <input type="hidden" ng-model="newStudent.id" />

        <input type="button" value="Save" ng-click="saveRecord()" class="btn btn-primary"/>

        <br />

        <br />

        <table border="1" bordercolor="blue">

            <tr style="color:blue">

                <th style="width:150px">Name</th>

                <th style="width:150px">Address</th>

                <th style="width:150px">Dept</th>

                    <th>Action</th>

            </tr>

            <tr style="color:pink" ng-repeat="student in students">

                <td>{{ student.name }}</td>

                <td>{{ student.address }}</td>

                <td>{{ student.dept }}</td>

                <td>

                    <a  href="#" ng-click="edit(student.id)">edit</a> | 

                    <a href="#" ng-click="delete(student.id)">delete</a>

                </td>

            </tr>

        </table>

    </div>

</body>
 </html>

 

STEP2: Create an angularCrud.js file which will be our controller.

  • Create an angular module and specify a name to it

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

  • Create a controller

app.controller('myctrl',function($scope){});

Now we will create all the CRUD functions one by one

  • CREATE FUNCTION:

$scope.saveRecord = function () {

if ($scope.newStudent.id == null) {

$scope.newStudent.id = empid++;

$scope.students.push($scope.newStudent);

} else {

for (i in $scope.students) {

if ($scope.students[i].id == $scope.newStudent.id) {

$scope.students[i] = $scope.newStudent;

}

}

}

$scope.newStudent = {};

}

The saveRecord() function does two things. One, if it’s a new student we will take the properties from newStudent that came from the template, and push that object in the local address collection. The address collection is then assigned to the model’s collection in the view.

  • EDIT and DELETE FUNCTION:

First, we have provided the delete functionality. For this, we have created a function named “delete”. In this function the Id of the Student is passed, if the Id correctly matches one of the existing Ids then the delete operation will be executed and that entry will be deleted.

Similarly, we have created the “Edit” function. In this function the Id of the Student will also be passed but this time the data related to that Id will not be deleted, instead it will be passed back to the corresponding input boxes so that the user can make changes and when the user clicks the save button the data will again be saved at the same Id position as it was stored previously.

  • Now the Updated angularCrud.js script looks like this –

$scope.delete = function (id) {

for (i in $scope.students) {

if ($scope.students[i].id == id) {

$scope.students.splice(i, 1);

$scope.newStudent = {};

}

}

}

$scope.edit = function (id) {

for (i in $scope.students) {

if ($scope.students[i].id == id) {

$scope.newStudent = angular.copy($scope.students[i]);

}

}

}

Output:

crud operations in angular - edurekaWith this, we have come to the end of this blog on CRUD Operations in AngularJS. I hope reading this blog will help you with your problems related to CRUD operations and makes you capable to use CRUD operations in AngularJS. 

Keep visiting, Keep learning!

If you wish to learn more about Angular framework, then check out our Angular Training & Certification which comes with instructor-led live training and real-life project experience. This training will help you understand Angular in-depth and help you achieve mastery over the subject.

Got a question for us? Please mention it in the comments section of ” crud operations in  Angularjs?” and I will get back to you.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.