AngularJs App

A

Crud Application Using AngularJs

Why Is It Special

Angular JS is a JavaScript-based open-source front-end web application framework mainly maintained by Google and it is used for building MVC based applications.

So,Guys today we make an angular js app which perform crud operation

We basically perform 4 operations.

  • 1 : Create
  • 2 : Read
  • 3 : Update
  • 4 : Delete

We understand each and every topic in breifly as we use them in our Applicaion

This is an image of our application that how it look like.
So,first of all we make our directory structure like that :
  • CSS

    • bootsrap.min.css
    • style.css
  • JS

    • boostrap.min.js
    • index.js
    • jquery.min.js
  • lib

    • angular.min.js
    • app

      • app.js
  • includes

    • connection.php
    • insert-form.php
    • update-form.php
    • select.php
    • insert.php
    • update.php
    • delete.php
  • index.php

For this application we use realtional database MYSQl

We should create database name Employees

Here is the link where you can download dummy database Download

So, you import in your database name employee

Now we are ready to start our main logic

our index.php would be seen like that


<!Doctype html>
<html lang="en" ng-app="crud">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <link rel="icon" href="">
    <title>Crud Operation Using AngularJS</title>
    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="lib/angular1.6.js"></script>
    <script src="lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
</head>
<body>
  <div class="container wrapper" ng-controller="crudcontroller">
        <h1 class="text-center">AngularJS CRUD Operations <small><small><small>with pagination.</small></small></small>
        </h1>
        <nav class="navbar navbar-default">
            <div class="d-flex" style="width:100%;">
                <div class="alert alert-default navbar-brand search-box">
                    <button class="btn btn-primary" ng-click="formToggle()">Add Employee </button>
                </div>
                <div class="alert alert-default input-group search-box">
                    <div class="input-group-btn" style="width:100%;">
                        <input type="text" class="form-control" placeholder="Search Employee Details from Database..." ng-model="search">
                    </div>
                </div>
            </div>
        </nav>
        <div class="row justify-content-center">
            <div class="col-md-6 "> 
                <div class="text-center" >
                    <img src="img/giphy.gif" ng-show="loading" alt="">
                </div>
                <!-- Include insert form to insert data into database -->
                <div ng-include src="'templates/form.php'" ng-show="show_form"></div>

                <!-- Include update form to edit and update data into database -->
                <div ng-include src="'templates/editform.php'" ng-show="edit_form"></div>
            </div>
        </div>

        <!-- Table to show employee detalis -->
        <div class="table-responsive">
            <table class="table table-hover">
                <tr>
                    <th>Sno.</th>
                    <th>Emp ID</th>
                    <th>Employee Name</th>
                    <th>Email Address</th>
                    <th>Gender</th>
                    <th>Address</th>
                    <th></th>
                    <th></th>
                </tr>
                <tr ng-repeat="detail in filteredItems| filter:search">
                    <td><span>{{$index+1}}</span></td>
                    <td>{{detail.emp_id}}</td>
                    <td>{{detail.emp_name}}</td>
                    <td>{{detail.emp_email}}</td>
                    <td>{{detail.emp_gender}}</td>
                    <td>{{detail.emp_address}}</td>
                    <td>
                        <button class="btn btn-secondary" ng-click="editinfo(detail)" title="Edit">Edit</button>
                    </td>
                    <td>
                        <button class="btn btn-danger" ng-click="deleteinfo(detail)" title="Delete">Delete</button>
                    </td>
                </tr>
            </table>
        </div>
        <!--  Pagination   -->
         <div  data-pagination="" data-num-pages="numOfPages()" 
          data-current-page="curPage" data-max-size="maxSize"  
          data-boundary-links="true">
         </div>
    </div>
    <!-- Bootstrap core JavaScript==================================================- ->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="js/crud.js"></script>
    <script src="js/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

STEP 1

Read From database

First we create angular module name crud and controller name crudcontroller

then we call funtion get_employee_detail() which get details from select.php using http request then it pass details to $scope.details object

our select.php retrive data from database using select query after that we encode it into Json format because angular reads data in json format

We also use here pagination logic and put loder before table until all details would load.which we discuss later in this section.


var crud = angular.module("crud", ["ui.bootstrap"]);
crud.controller('crudcontroller', function ($scope, $http, $log) {
    
    function get_employee_detail() {
        $http.post("includes/empdetail.php")
            .then(function (response) {
                $scope.details = response.data;     //pass data into details object
                //console.log($scope.details);  
                $scope.curPage = 1,                 //pagination logic
                $scope.itemsPerPage = 5,
                $scope.maxSize = 5;
                $scope.numOfPages = function () {
                    return Math.ceil($scope.details.length / $scope.itemsPerPage);
                };
                $scope.$watch('curPage + numPerPage', function () {
                    var begin = (($scope.curPage - 1) * $scope.itemsPerPage),
                        end = begin + $scope.itemsPerPage;
                    $scope.filteredItems = $scope.details.slice(begin, end);
                });
            }, function () {
                alert('error occured');
            }).finally(function(){
              $scope.loading = false;    //loading image dissapear
        });
    };
    get_employee_detail();   // select employee details
    $scope.loading =true;    //loading image appeaar
        
                            

<?php
include('connection.php');
?>
<?php
    $query = "SELECT * FROM emp_details";
    $result  = mysqli_query($con,$query);
    $arr  = array();
        if($result)
        {
            while($row = mysqli_fetch_assoc($result))
            {
                $arr[] = $row;
            }
        }
    $json = json_encode($arr); //encode into json format
    echo $json;
?>
                            

STEP 2

Now we have to insert data into our database.

For these we have to make insert form in insert.php which we include in our index page using ng-include directive


<div class="jumbotron mr-auto mb-4 pt-3 pb-4" id="empform" >
   <h2 class="text-info">Register Yourself</h2>
    <form  action="" class="form"  ng-submit="insertvalue(emp)" name="myform" > 
        <div class="form-group ">
            <label for="">Name</label>
            <input type="text" class="form-control" name="name" ng-model="emp.name" autofocus>
            <div class="form-group text-danger" ng-show="myform.name.$invalid && myform.fname.$dirty">
               Name field is empty
            </div>
        </div>
        <div class="form-group">
            <label for="">Email</label>
            <input type="email" class="form-control " name="email" ng-model="emp.email" autofocus >
            <div class="form-group text-danger" ng-show="myform.email.$invalid && myform.email.$dirty">
                Invalid email
            </div>
        </div>
        <div class="custom-control custom-radio custom-control-inline mt-2 mb-2 ">
            <input type="radio" id="customRadioInline1" value="male" name="gender" class="custom-control-input" ng-model="emp.gender">
            <label class="custom-control-label" for="customRadioInline1">Male</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline mt-2 mb-2">
            <input type="radio" id="customRadioInline2" value="female" name="gender" class="custom-control-input"  ng-model="emp.gender">
            <label class="custom-control-label" for="customRadioInline2">Female</label>
        </div>
        <div class="form-group">
            <label for="">Address</label>
            <textarea name="address" id="" cols="47" rows="1" class="form-control" ng-model="emp.address" autofocus ></textarea>
            <div class="form-group" ng-show="myform.address.$invalid && myform.address.$dirty">Address field is empty</div>
        </div>
        <div class="input-group mt-3">
        <button type="submit" class="btn btn-primary ml-1" ng-disabled="myform.$invalid">Submit</button>
        </div>
    </form>
</div>

                    

In our form we use ng-submit directive which pass emp as argument to insertvalue() function.

Every input field have ng-model directive which will bind and store data into emp.

We also use angularjs form validation so,that it prevents from empty and invalid data to pass.

In our crud.js we make insertvalue funtion which will sends data to insert.php using http service.

We also hide insert form until we click on add employee button as we click on it form appear


        $scope.insertvalue = function (emp) {
        $scope.message = "";
        //console.log(emp);
        var request = $http({
            method: "post",
            url: "includes/insert.php",
            data: {
                "name": emp.name,
                "email": emp.email,
                "gender": emp.gender,
                "address": emp.address
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });
        request.then(function (response) {
            $scope.message = "From PHP file : " + response.data;
            // var x = $scope.message;
            if (response.data == true) {
                get_employee_detail();        
                // Hide details insertion form
                $scope.show_form = false;     //hide insert form when data is submmitted
            }
        });
       
    }
    $scope.show_form = false;            //hide insert form
    $scope.formToggle = function () {
        $scope.show_form = $scope.show_form ? false : true;
    }
                    

In insert.php we first decode our data using json decode function of php.

After successful insertion of data it returns true as reponse and we again call our get_employee_detail() so,that we get latest update of data


<?php
require_once 'connection.php';
// Fetch and decode the  data
$data = json_decode(file_get_contents("php://input"));

$name = mysqli_real_escape_string($con, $data->name);
$email = mysqli_real_escape_string($con, $data->email);
$gender = mysqli_real_escape_string($con, $data->gender);
$address = mysqli_real_escape_string($con, $data->address);

// mysqli insert query
$query = "INSERT into emp_details (emp_name,emp_email,emp_gender,emp_address) VALUES ('$name','$email','$gender','$address')";
// Inserting data into database
mysqli_query($con, $query);
echo true;    //returns true 
?>
                   

STEP 3

Now we have to update our data into database

For these we have to make update form in update.php Simillarly we include in our index.php using ng-include directive


<div class="jumbotron mr-auto mb-4 pt-3 pb-4" id="empform" >
   <h2 class="text-info">Edit details</h2>
    <form  action="" class="form"  ng-submit="updateform(edit)" name="myform" > 
        <div class="form-group ">
            <label for="">Name</label>
            <input type="text" class="form-control" name="name" ng-model="edit.emp_name" value="{{edit.emp_name}}" autofocus>
            <div class="form-group text-danger" ng-show="myform.name.$invalid && myform.fname.$dirty">
               Name field is empty
            </div>
        </div>
        <div class="form-group">
            <label for="">Email</label>
            <input type="email" class="form-control "value="{{edit.emp_email}}" name="email" ng-model="edit.emp_email" autofocus >
            <div class="form-group text-danger" ng-show="myform.email.$invalid && myform.email.$dirty">
                Invalid email
            </div>
        </div>
        <div class="custom-control custom-radio custom-control-inline mt-2 mb-2 ">
            <input type="radio" id="customRadioInline1" value="male" name="gender" class="custom-control-input" ng-model="edit.emp_gender">
            <label class="custom-control-label" for="customRadioInline1">Male</label>
        </div>
        <div class="custom-control custom-radio custom-control-inline mt-2 mb-2">
            <input type="radio" id="customRadioInline2" value="female" name="gender" class="custom-control-input"  ng-model="edit.emp_gender">
            <label class="custom-control-label" for="customRadioInline2">Female</label>
        </div>
        <div class="form-group">
            <label for="">Address</label>
            <textarea name="address" id="" cols="47" rows="1" class="form-control" ng-model="edit.emp_address" autofocus value="{{edit.emp_address}}"></textarea>
            <div class="form-group" ng-show="myform.address.$invalid && myform.address.$dirty">Address field is empty</div>
        </div>
        <div class="input-group mt-3">
        <button type="submit" class="btn btn-primary ml-1" ng-disabled="myform.$invalid">Submit</button>
        </div>
    </form>
</div>

                    

When we click on edit button then all information contain in paricular row pass as an argument in editinfo function

then passed argument is stored in new scope property name $scope.edit,which is used during display data on update form.

Simillarly as insert form we make updateform() function which pass edit as argument to update.php which contain all input field data


$scope.edit_form = false;  //hide update form
    $scope.edit = {};
    $scope.editinfo = function (emp) { 
        $scope.edit_form = true;    //when user click on edit button
        $scope.edit = emp;          // it pass all data from emp to edit object
        console.log($scope.edit);
    }
       $scope.updateform = function (emp) {
       $http.post("http://localhost/angular_crud/includes/update.php", {
            "id": emp.emp_id,
            "name": emp.emp_name,
            "email": emp.emp_email,
            "gender": emp.emp_gender,
            "address": emp.emp_address
        }).then(function (response) {
            $scope.msg2 = response.data;
            if ($scope.msg2 == true) {
                $scope.edit_form = false;     // hide update form
            }
        });
    }

                    

In update.php we do same operation as insert.php


<?php
require_once 'connection.php';
$data = json_decode(file_get_contents("php://input")); //json decode
$id = mysqli_real_escape_string($con, $data->id);
$name = mysqli_real_escape_string($con, $data->name);
$email = mysqli_real_escape_string($con, $data->email);
$gender = mysqli_real_escape_string($con, $data->gender);
$address = mysqli_real_escape_string($con, $data->address);
// mysqli query to insert the updated data
$query = "UPDATE emp_details SET emp_name='$name',emp_email='$email',emp_gender='$gender',emp_address='$address' WHERE emp_id=$id";
mysqli_query($con, $query);
echo true; //return true
?>
                

STEP 4

Now we have to delete our data from employee table

When we click on delete button it collects all data from its row and pass as an argument to a delete function which pass data to delete.php


     $scope.deleteinfo = function (emp) {
        $http.post("http://localhost/angular_crud/includes/delete.php", {
            "id": emp.emp_id
        }).then(function (response) {
            $scope.msg3 = response.data;
            get_employee_detail();
        });
    }

In response, it delete row from employee table and again call get_employee_detail() to show remaining rows in employee table.


<?php
include 'connection.php';
$request = json_decode(file_get_contents("php://input"));
$id = mysqli_real_escape_string($con,$request->id);
$query ="DELETE FROM emp_details where emp_id ='$id'";
mysqli_query($con,$query);
echo  "true";    //return true
?>
               

STEP 5

Finishing Touch to our application

Finally we complete our crud operation but now we apply pagination in our employee table because when table size increases it goes out of the viewport and you have to scoll so long to get employee detail.

So,we are using angularjs pagination directive for bootstrap you can download it from https://angular-ui.github.io/bootstrap/

As soon as you've got all the files downloaded and included in your page you just need to declare a dependency on the ui.bootstrap module:

    
<script src="lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
                    

var crud = angular.module("crud", ["ui.bootstrap"]);    //inject as a dependency 
crud.controller('crudcontroller', function ($scope, $http, $log) {
    
    function get_employee_detail() {
        $http.post("includes/empdetail.php")
            .then(function (response) {
                $scope.details = response.data;     //pass data into details object
                //console.log($scope.details);  
                $scope.curPage = 1,                 //pagination logic
                $scope.itemsPerPage = 5,
                $scope.maxSize = 5;
                $scope.numOfPages = function () {
                    return Math.ceil($scope.details.length / $scope.itemsPerPage);
                };
                $scope.$watch('curPage + numPerPage', function () {
                    var begin = (($scope.curPage - 1) * $scope.itemsPerPage),
                        end = begin + $scope.itemsPerPage;
                    $scope.filteredItems = $scope.details.slice(begin, end);
                });
            }, function () {
                alert('error occured');
            }).finally(function(){
              $scope.loading = false;    //loading image dissapear
        });
    };
    get_employee_detail();   // select employee details
    $scope.loading =true;    //loading image appeaar
        
                            

here is the logic for pagination ,in which we set only 5 rows per page


<div data-pagination="" data-num-pages="numOfPages()" 
          data-current-page="curPage" data-max-size="maxSize"  
          data-boundary-links="true">
</div>

When we retrive our data first time from database.It takes some time to display,which could not look preety good our table show empty rows,to make it look better we put loader on it,unitl whole data is retrived.


<div class="text-center" >
    <img src="img/giphy.gif" ng-show="loading" alt="">
</div>
                   

As we declare ng-show attribute loading true in our crud.js and when we get all details then we make it false.

I hope guys you enjoy this tutorial and to clarify your doubts you can comment below.

Please Share this tutorial so that other may get help and learn from this tutorial