Creating simple inline editing with AngularJS

By | July 14, 2015

Inline editing is the tool which is required by us most of the time in almost all of our applications. Now-a-days with modern web technologies no one wants different pages for display and edit contents like earlier we had viewprofile and editprofile pages. It gives an amazing user experience when the user wants to edit some content and upon his click the display content instantly changes to the editable one and it can be saved and refreshed instantly without being going to a different page.

In this tutorial we will learn about creating an inline editing system using AngularJS. Here I assume you have the basic knowledge of AngularJS.

Basic Idea

Let’s have a basic idea what we are going to do first.

inline

Every time the content is loaded I will check if it is set to be displayed or edited and on the basis of this value I will call my script which contains nothing but the HTML for display and edit respectively.

Example

Let us take an example and that will help us understand the situation better.

I have an array of customers, we will list them in a table using ng-repeat and then add some functions for the inline editing functionality.

Code

Let us first display all the customer using ng-repeat.

<table class="table table-striped table-bordered">
 <thead>
  <th>Employee Name</th>
  <th>Employee Email</th>
  <th>Employee Salary</th>
  <th>Active</th>
  <th>Edit</th>
 </thead>
 <tbody>
  <tr ng-repeat="employee in employees">
   <td>{{employee.empName}}</td>
   <td>{{employee.empEmail}}</td>
   <td>{{employee.empSalary | currency:"&#8377;"}}</td>
   <td>{{employee.active | active}}</td>
   <td>
    <button type="button" class="btn btn-primary">Edit</button>
    <button type="button" class="btn btn-danger">Delete</button>
   </td>
  </tr>
 </tbody>
<table>

Here employees is array of employee data and we are iterating to each employee using ng-repeat directive. This is a simple use of ng-repeat, we will modify it according to our needs to build an in-line editing system, but first lets have a look how does it look.

table using ng-repeat

table using ng-repeat

Here I have two buttons edit and delete, delete will simply delete the entry from the database using HTTP request our main focus here is on edit button which will turn this display mode to editing. Let us move ahead and make some changes to the code in order to make it functional.

The first change we will make is add ng-include directive which will call a function getTemplate() and this function will take a parameter which is nothing but a single employee from employees array.

<tr ng-repeat="employee in employees" ng-include="getTemplate(employee)">

getTemplate() is very simple and will check is the employee passed in the parameter is set to be displayed or edit and accordingly we will call a script of the html content.

$scope.getTemplate = function (employee) {
 if (employee.empID === $scope.selected.empID){
  return 'edit';
 }
 else return 'display';
};

As you can see the above code is very simple, the thing which might confuse you is the if condition here. Let me make it more clear here employee is the value passed as a parameter and $scope.selected is an JSON object which will hold the employee data upon being selected to edit, and is initially set to null.

$scope.selected = {};

So lets have a look to the function which is called on clicking the edit button and what happens to this $scope.selected object.

$scope.editEmployee = function (employee) {
 $scope.selected = angular.copy(employee);
};

Here I have made use of anuglar function copy which will copy the contents from one to another and here we are copying the contents of the parameter passed(employee) to $scope.selected object, so now the $scope.selected object is not null and the getTemplate() function returns edit for one employee which will call the edit script instead of display script.

edit functionality

edit functionality

I have mentioned a couple of times now that we will call different scripts for edit and display, so lets have a look at how these scripts look. Below is the full code for the HTML part.

<table class="table table-striped table-bordered">
 <thead>
  <th>Employee Name</th>
  <th>Employee Email</th>
  <th>Employee Salary</th>
  <th>Active</th>
  <th>Edit</th>
 </thead>
 <tbody>
  <tr ng-repeat="employee in employees" ng-include="getTemplate(employee)">
   <script type="text/ng-template" id="display">
    <td>{{employee.empName}}</td>
    <td>{{employee.empEmail}}</td>
    <td>{{employee.empSalary | currency:"&#8377;"}}</td>
    <td>{{employee.active | active}}</td>
    <td>
     <button type="button" class="btn btn-primary" ng-click="editEmployee(employee)">Edit</button>
     <button type="button" class="btn btn-danger" ng-click="deleteEmployee(employee)">Delete</button>
    </td>
   </script>
   <script type="text/ng-template" id="edit">
    <td><input type="text" ng-model=employee.empName class="form-control input-sm"/></td>
    <td><input type="text" ng-model=employee.empEmail class="form-control input-sm"/></td>
    <td><input type="text" ng-model=employee.empSalary class="form-control input-sm"/></td>
    <td>
      <select class="form-control input-sm" ng-model=employee.active>
        <option value='1'>Yes</option>
        <option value='0'>No</option>
      </select>
    </td>
    <td>
     <button type="button" class="btn btn-primary" ng-click="updateEmployee(employee)">Save</button>
     <button type="button" class="btn btn-danger" ng-click="reset()">Cancel</button>
    </td>
   </script>
  </tr>
 </tbody>
<table>

Above code doesn’t have much changes to it, we have simply added two script tags and given them unique id display and edit, so the value we return from the getTemplate() is the actually the id of the script which we will call and the contents of that script will be displayed.

Let us see how the screen looks when we click on edit button.

edit mode table

edit mode table

Again you can see two buttons, save and cancel. Save button will save the changes which can be achieved by making an HTTP request to the database and cancel button should cancel the changes. As we know a particular employee is editable because it exists in $scope.selected so upon cancel we can clear the $scope.selected object.

$scope.reset = function () {
$scope.selected = {};
};

All Done 🙂 Hope you enjoyed it.

This is how you can create a simple in-line editing system, for a live demo of this you can view my recorded webinar of the same.

Source Code – inline-editing-in-ng

30 thoughts on “Creating simple inline editing with AngularJS

  1. bala

    Nice article. Please provide downloadable entire solution code.

    Reply
    1. shubham0987 Post author

      Thank you Bala. I have uploaded the source code containing PHP files also, find it in the of the article.

      Reply
    1. Harsh

      What happens after click on ‘Save’ button. I used “return ‘display’ ” for returning back to display mode, but it is not working. Kindly complete your article, it is still incomplete. Hope for your prompt reply.

      Reply
      1. shubham0987 Post author

        Hi Harsh,

        As mentioned in the article it “can be achieved by making an HTTP request to the database”.
        It depends on what backend you are using. I have a sample PHP code, I will be glad if it can be of any help to you.


        $scope.savePayment = function () {
        var res = $http.post('pages/ngProcess.php',
        {
        action : 'updatePayment',
        data : $scope.selected
        });
        res.success(function(data, status, headers, config) {
        $scope.message = data;
        document.getElementById("message").textContent = data;
        });
        res.error(function(data, status, headers, config) {
        $scope.message = "Error adding to DB"
        document.getElementById("message").textContent = $scope.message;
        });
        $scope.reset();
        };

        PHP Code:

        //To get the data passed via AngularJS “pages/ngProcess.php”

        $postdata = file_get_contents("php://input");
        $postdata = json_decode($postdata);
        $action = $postdata->action;
        $data = $postdata->data;

        //depending on action I will call my PHP method

        if($action == "updatePayment"){
        $cmd = "your sql query to update";
        $com = $database->conn->prepare($cmd);
        $com->execute();
        }

        Reply
        1. Harsh

          Hi, thanks I can understand that you are working on backend but here the problem is that after your data gets into db the input tag section should be replaced with non-input section that is display part. Now when I click on save data is being saved but input tag is not turning back to display and it is still showing to input the new data. Hope you are getting what I am telling. So, this is the problem

          Reply
          1. shubham0987 Post author

            on HTTP success or failure try calling the reset function or simply clear the selected variable.

            $scope.selected = {};

  2. gopinath

    i am trying to do this without $http, i use two object initially in employees array and insted of validating and creating a form and adding to DB i am created a button to add row.without accesing DB i am here trying to do but i am confussed with getTemplate(). i need to know is there any way to use if condition with out accessing the database.

    Reply
  3. shwetha

    hi this my code i m facing problem in editing and saving button code can anybody help me

    employee list

    Create Person

    Add Person

    Name

    Age

    Title

    {{ person.name }}

    {{ person.age }}

    {{ person.title }}

    Remove

    edit

    edit

    function ExampleCtrl($scope){
    $scope.people = [];

    $scope.addPerson = function(){

    var person = {
    name: $scope.name,
    age: $scope.age,
    title: $scope.title

    };
    $scope.editlisting=false;

    $scope.people.push(person);
    };
    $scope.editUser = function(person) {

    $scope.editlisting=true;
    $scope.exitlisting=person;
    };
    $scope.save=function(person)
    {
    $scope.exitlisting={};
    $scope.editlisting=false;
    };

    $scope.removePerson = function(index){
    $scope.people.splice(index, 1);
    };
    };

    Reply
  4. Gowritha

    Its working fine for me while inserting the records in DB. But it is not listing the records in the browser, it shows the error. And then we need to check the edit and delete function. Thanks please advice..

    Reply
  5. Gowritha

    Please send the working file of above “Creating simple inline editing with AngularJS “

    Reply
  6. Harsh

    Hi Shubham ,
    The second part of the code as below –

    $scope.getTemplate = function (employee) {
    if (employee.id=== $scope.selected.id){
    return ‘edit’;
    }
    else return ‘display’;
    };

    I am getting that ” Cannot read property ‘id’ of undefined ” in the console for the lines having employee.id and $scope.selected.id . can you tell what is the reason ? If I am removing the .id from both the objects then nothing is coming in console but it is not working as usual as it should be. Can you please help
    ?

    Reply
  7. HIRENKUMAR CHHAYA

    hi I am new to angular. It is great article. It is quite helpful to me because same thing I want to do in my project. Now I am able to do same thing but I have many records So I want to do paging as well. For that instead of ng-repeat, I am using dir-paginate and dir-pagination-controls which cause problem(unable to render my data). Can you please provide solution to this.

    Reply
  8. Shanu

    It does not seem to work with dir-paginate. Please provide a solution for the same.

    Reply
  9. Omar

    Do you happen to know how to do this without using script tags in the html?

    Reply

Leave a Reply

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