Skip to main content
smart-table-add-edit-delete

AngularJS Smart Table with Add, Edit and Delete Records

This is Part II of angularjs smart-table tutorial.This smart-table tutorial help to add, edit and delete records using rest api. I am using angularjs Bootstrap modal directive to show view record modal window, add record modal window, and edit record modal window.

I am extending my previous tutorials AngularJS Smart Table Listing with pagination, sorting and searching and will add crud operation on existing source code.

I am using JSON data-based rest API which will use to add a record into the smart table, update record data into smart-table and delete a record from the database. I am using Dummy Rest API for testing purposes. You can also integrate this example code with your server-side application.

AngularJS is most popular front-end JavaScript framework and smart-table is most customizable and awesome angularjs grid plugin.I will let know, how to add functionality in angularjs smart-table for add, edit and delete record.I am assuming you have read my previous tutorials.

Video Tutorial

If you are more comfortable in watching a video that explains about AngularJS Smart Table with Add, Edit and Delete Records, then you should watch this video tutorial.

Simple Example of Smart Table With Add, Edit and Delete Data

smart-table-add-edit-delete

I will describe the step-by-step implementation of smart-table with add, edit and delete record operation. There are many ways you can do that, You can use router to show add, edit HTML page or you can use inline editing in smart-table. I am using Bootstrap modal Box to show add, edit and view window with separate controller and HTML file.

I will use following files in this smart table tutorial,

  1. index.html : This file will contain all HTML markup and initialize angularjs application.
  2. app.js : This file will contain angularjs controllers code and scope methods.
  3. view/view_record.html : This file will contain view record form.
  4. view/add_record.html : This file will contain add record form.
  5. view/update_record.html : This file will contain update record form.

Also Checkout other tutorials of angular grid,

How to Integrate Angularjs Bootstrap UI Modal Box

We will add the bootstrap UI file in the head section of index.html file, if you have already included please ignore it. You can read more from Angular Bootstrap Modal Example Using Boostrap UI.

<script src="/assets/libs/angular-ui-bootstrap/ui-bootstrap-tpls-1.3.0.min.js" type="text/javascript"></script>

now we will add bootstrap UI dependency in angularjs application and inject it into app.js file.

TestApp = angular.module('TestApp', ['TestApp.controllers', 'smart-table', 'ui.bootstrap']);

The next action will be, to add action buttons to smart-table, so we will add the following HTML into the action column in the table.

<div class="btn-group" role="group" aria-label="...">&nbsp;</div>

The above steps will integrate the bootstrap Modal box and add actions link buttons against each row records in smart table.

How to inject modal in controller

We have included bootstrap UI in angularjs application but we need to include a modal box directive in our application controller where to show the modal box. We need to create a modalInstance variable and assigned null value.

angular.module('TestApp.controllers', []).controller('testController',  ['$scope', '$http', '$uibModal', function($scope, $http, $modal) {
var modalInstance = null;
});

How To add View Record in smart-table

We will show the view record modal box on-click of view icons, I am passing row id that will use for fetch records and send data to view modal scope.

Step 1: We will add a method on ng-click event, The view action HTML code will become like below,

<button class="btn btn-info" type="button"><i class="glyphicon glyphicon-search"></i></button>

Step 2: Created view_record.html file and add the below HTML code into this file.

<div class="clearfix">
  <div class="modal-header model-grey-color">
		<button type="button" class="close" data-dismiss="modal" aria-label="Close" ng-click="cancelModal()"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title">View : {{employee.employee_name}}</h4>
  </div>
  <div class="modal-body">
	<dl class="dl-horizontal">
	  <dt>Name</dt>
	  <dd>{{employee.employee_name}}</dd>
	  <dt>Age</dt>
	  <dd>{{employee.employee_age}}</dd>
	  <dt>Salary</dt>
	  <dd>{{employee.employee_salary}}</dd>
	</dl>
  </div>
  <div class="modal-footer">
    <button class="btn btn-danger" ng-click="cancelModal()"><i class="fa fa-close"></i> Close</button>
  </div>
</div>

Step 3: We will define this method on testController and configure modal box parameters.

$scope.viewRecord = function(id){
	if(id > 0) {
	  $http.get("https://dummy.restapiexample.com/api/v1/employee/"+id)
		.then(function(response){
			modalInstance = $modal.open({
			  animation: false,
			  templateUrl: 'view/view_record.html',
			  controller: 'empViewCtrl',
			  scope: $scope,
			  size: '',
			  resolve: {
				  record: function () {
					  return response.data;
				  }
			  }
		   });
		});
	 
	}
}

Above code Line #3 we have to define HTTP request that will fetch records using API, Line #5 create a modal instance and passed HTML file path (‘view/view_record.html’) and controller name(’empViewCtrl’) which will handle requests.

In the last method, we have passed the response.data object to the modal controller. You can get this response data on empViewCtrl controller by accessing 'record' object.

Step 4: Define 'empViewCtrl' controller and create init() method that will set record data into scope variable.

TestApp.controller('empViewCtrl',  ['$scope', '$http', 'record', function($scope, $http, record) {
	function init(){
        $scope.employee = record;
    }
	init();
	
}]);

How To Add New Record in smart-table

We will show add record modal box and the user will fill in all required data. finally, we will call saveRecord() method that will parse JSON data and send Data to the Rest API Method. I am refreshing smart-table grid data after the successfully inserted record in MySQL DB.

Step 1: We will add a new button to add records, we will bind ng-click event to show add modal window.

<div class="row well"><button class="btn btn-info pull-right" type="button"><i class="glyphicon glyphicon-plus"> </i> Add New Employee</button></div>

Step 2: Created add_record.html file and added below HTML code into this file.

<div class="clearfix">
<div class="modal-header model-grey-color"><button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>&nbsp;</p>
<h4 class="modal-title">Add Emp</h4>
</div>
<div class="modal-body"><form class="form-horizontal" role="form">
<div class="form-group"><label class="col-sm-3 control-label">Name <sup class="sup-color">*</sup></label>
<p>&nbsp;</p>
<div class="col-sm-8"><input class="form-control" type="text" placeholder="Employee Name"></div>
<p><span class="help-button">?</span></p>
</div>
<div class="form-group"><label class="col-sm-3 control-label">Age <sup class="sup-color">*</sup></label>
<p>&nbsp;</p>
<div class="col-sm-8"><input class="form-control" type="number" placeholder="Employee Age"></div>
<p><span class="help-button">?</span></p>
</div>
<div class="form-group"><label class="col-sm-3 control-label">Salary <sup class="sup-color">*</sup></label>
<p>&nbsp;</p>
<div class="col-sm-8"><input class="form-control" type="number" placeholder="Employee Salary"></div>
<p><span class="help-button">?</span></p>
</div>
</form></div>
<div class="modal-footer model-grey-color"><button class="btn btn-success"><i class="glyphicon glyphicon-floppy-save"></i> Save</button> <button class="btn btn-danger"><i class="glyphicon glyphicon-remove"></i> Close</button></div>
</div>

Step 3: We will define addRecord() method on testController and configure modal box parameters.

$scope.addRecord = function(){
	modalInstance = $modal.open({
	  animation: false,
	  templateUrl: 'view/add_record.html',
	  controller: 'addEmpCtrl',
	  scope: $scope,
	  size: '',
	  resolve: {
	  }
   });

}

Line #2 create modal instance and passed HTML file path ('view/add_record.html') and controller name('addEmpCtrl') which will handle requests.

Step 4: Define 'addEmpCtrl' controller and create saveEmp() method that will set validate input data, parse data, and send data to REST API Method.

TestApp.controller('addEmpCtrl',  ['$scope', '$http', 'record', function($scope, $http) {
	$scope.saveEmp = function () {
		$scope.datas = {};

		if(!angular.isDefined($scope.employee_name) || $scope.employee_name === '') {
			alert('employee name is empty');
			return;
		}
		else if(!angular.isDefined($scope.employee_age) || $scope.employee_age === '') {
			alert('employee age is empty');
			return;
		}else if(!angular.isDefined($scope.employee.salary) || $scope.employee.salary === '') {
			alert('employee salary is empty');
			return;
		} else {
			$scope.datas.name = $scope.employee_name;
			$scope.datas.age = $scope.employee_age;
			$scope.datas.salary = $scope.employee_salary;
			console.log($scope.datas);
		}
		$scope.cancelModal();
		$scope.saveRecord($scope.datas);
	};
	
}]);

How To Update Record in smart-table

These steps will demonstrate updation of records into the table using REST API. I am refreshing smart-table grid data on the successfully update records.

Step 1: We will add a method on ng-click an event that will show the edit window.

<div class="row well">&nbsp;</div>

Step 2: Created update_record.html file and added below HTML code into this file.

<div class="clearfix">
<div class="modal-header model-grey-color"><button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>&nbsp;</p>
<h4 class="modal-title">View : {{employee.employee_name}}</h4>
</div>
<div class="modal-body">
<dl class="dl-horizontal">
<dt>Name</dt>
<dd>{{employee.employee_name}}</dd>
<dt>Age</dt>
<dd>{{employee.employee_age}}</dd>
<dt>Salary</dt>
<dd>{{employee.employee_salary}}</dd>
</dl>
</div>
<div class="modal-footer"><button class="btn btn-danger"><i class="fa fa-close"></i> Close</button></div>
</div>

Step 3: We will define editRecord() method on testController and configure modal box parameters.

$scope.editRecord = function(id){
   if(id > 0) {
	  $http.get("https://dummy.restapiexample.com/api/v1/employee/"+id)
		.then(function(response){
			modalInstance = $modal.open({
			  animation: false,
			  templateUrl: 'view/update_record.html',
			  controller: 'updateEmpCtrl',
			  scope: $scope,
			  size: '',
			  resolve: {
				  record: function () {
					  return response.data;
				  }
			  }
		   });
		});
   }

}

Line #5 create modal instance and passed HTML file path('view/add_record.html') and controller name('addEmpCtrl') which will handle request.

Step 4: Define 'updateEmpCtrl' controller and create updateEmp () method that will set validate input data, parse data and sent data to REST API Method.The init() method use for set data into employee scope variable.

TestApp.controller('updateEmpCtrl',  ['$scope', '$http', 'record', function($scope, $http, record) {
	$scope.employee = {};
	function init(){
		$scope.employee.name = record.employee_name;
		$scope.employee.age = parseInt(record.employee_age);
		$scope.employee.salary = parseInt(record.employee_salary);
		$scope.employee.id = parseInt(record.id);
    }
	$scope.updateEmp = function () {
		$scope.cancelModal();
		if(!angular.isDefined($scope.employee.name) || $scope.employee.name === '') {
                alert('employee name is empty');
                return;
            }
            else if(!angular.isDefined($scope.employee.age) || $scope.employee.age === '') {
                alert('employee age is empty');
                return;
            }else if(!angular.isDefined($scope.employee.salary) || $scope.employee.salary === '') {
                alert('employee salary is empty');
                return;
            }
		$scope.updateRecord($scope.employee);
	}
	init();
	
}]);

How To Delete Record in smart-table

This step will demonstrate the deletion of records from the database table using REST API. I am refreshing smart-table grid data on the successfully deleted record.

Step 1: We will add a method on ng-click event to delete records. We will pass the record id as a parameter within method.

<button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-trash">
	</i></button>

Step 2 : We will define deletRecord() method on testController and configure modal box parameters.

$scope.deletRecord = function(id) {
		if (confirm('Are you sure you want to delete this?')) {
			 $http.delete("https://dummy.restapiexample.com/api/v1/delete/"+id)
			.then(function(response){
				console.log(response);
			});
		}
		
	}

I am using JavaScript confirm box to delete records, once the user clicks on ‘OK’ option, we will fire an ajax request to delete records from the database.

You can download the source code and Demo from the below link.

Conclusion

This tutorial help to create basic crud operation on smart-table listing. You can add a record, edit a record, view data, and delete a record from the database using REST API. I use PHP Rest API for all crud operations, You can replace REST calls as per your need.

14 thoughts to “AngularJS Smart Table with Add, Edit and Delete Records”

      1. Adam, the downloaded file only has app.js, index.html, user.jpg, and the views directory that has the add, update, and view record html files. There is no package.json. The project will not run. Using ‘ng serve’ just gives:
        You have to be inside an angular-cli project in order to use the serve command
        How are you running it on the host where your demo is ?
        Thank you.

        1. Never mind….I figured it out. Just open index.html in a browser. View, Edit, and Delete buttons don’t work, Add Employee does nothing. Left as an ‘exercise for the student’ ??? :>

Leave a Reply

Your email address will not be published. Required fields are marked *