Blog

01 Aug
2015

AngularJS Icon Logo

AngularJS and CRUD data binding


So lets start with what are AngularJS and CRUD?

NOTE: I posted an updated version using Angular 5, Laravel 5.6 to create a CRUD app using rest api calls via MySQL Create Angular Laravel CRUD app

First AngularJS (AngularJS link) is made by google, and is the new popular way of data manipulation (and more) direct in html with minimum code.

Second is the term CRUD which is an acronym for create, read, update and delete which simply relates to major functions that are implemented in relation to controlling data in applications.

With the tutorial you will be learning:

  • How to loop through an array of data and update a tables rows with this data
  • How to add a button to delete individual rows from the table
  • How to add a button to edit individual rows from the table
  • How to add a button to add new rows of data to a table

Tutorial for using AngularJS and data binding with CRUD

1. Create the file

So lets start by creating a new document like below and save it as 'angularjs-and-crud.html' and give it the title 'AngularJS and CRUD'.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS and CRUD</title>
</head>

<body>
</body>
</html>

On line 2 add the following 'ng-app="crudapp"', this tells AngularJS that this is our angularjs app and it classes this as the root, for this example I have named it 'crudapp'.

Also include the AngularJS external file, so for this example I am using Version 1.4.3.

<!doctype html>
<html ng-app="crudapp">
<head>
<meta charset="UTF-8">
<title>AngularJS and CRUD</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>

<body>
</body>
</html>

2. Create table and populate with data

Now lets create a table and populate it with some data so first allocate an application controller to the body tag and call it 'productController' - ng-controller="productController".

Then below that add our table to output the data to. The table is made of the following elements:

  • AngularJS ID: This is the automatic index/id that angularjs adds to data, so for this example I have it made it viewable. We also need this to detect which line of data to edit or delete later, but normally this would be an id from a database.
  • SKU CODE
  • PRODUCT
  • PRICE
  • QUANTITY

We are also using 'ng-repeat="product in listProducts"' to loop through and output the data we have added in the javascript. Here is how each element is working.

  • {{product.id = $index}}: This sets a unique id from the one AngularJS generates for each product.
  • {{product.sku}}: The products SKU Code
  • {{product.name}}: The products name
  • {{product.price}}: The products price
  • {{product.quantity}}: The products quantity

Now for the javascript, first lets define crudapp as a AngularJS application 'var crudapp = angular.module('crudapp', []);'.

Then add the controller for the application 'crudapp.controller' and the body tag as the root.

Lets also set the data array of our products to loop through in the table '$scope.listProducts'.

Here is how the files code should be looking now with its new lines of code highlighted.

<!doctype html>
<html ng-app="crudapp">
<head>
<meta charset="UTF-8">
<title>AngularJS and CRUD</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>

<body ng-controller="productController">

    <!-- Table to output data -->
    <table cellpadding="5" cellspacing="0" border="1">
    <thead>
            <tr>
                <th>AngularJS ID</th>
                <th>SKU CODE</th>
                <th>PRODUCT</th>
                <th>PRICE</th>
                <th>QUANTITY</th>
            </tr>
    </thead>
    <tbody>
            <tr ng-repeat="product in listProducts">
                <td>{{product.id = $index}}</td>
                <td>{{product.sku}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price}}</td>
                <td>{{product.quantity}}</td>
            </tr>
    </tbody>
    </table>

    <script type="text/javascript">

        // Define crudapp as a Angular application.
        var crudapp = angular.module('crudapp', []);

        // Application controller for the module.
        crudapp.controller('productController', function($scope){

            // Populate table with products data
            $scope.listProducts = [
                {sku:'SKU1', name:'Product Name 1', price:199, quantity: 50},
                {sku:'SKU2', name:'Product Name 2', price:220, quantity: 100},
                {sku:'SKU3', name:'Product Name 3', price:55, quantity: 25},
                {sku:'SKU4', name:'Product Name 4', price:100, quantity: 50},
                {sku:'SKU5', name:'Product Name 5', price:10, quantity: 1000}
            ];

        });
    </script>

</body>
</html>

Now preview the file in a browser you should see the table with the Products data array output.

angularjs and crud data binding 01

3. Add a Delete button to delete individual rows of data from the table.

Lets start by adding a another header cell to the table called 'OPTIONS' this will be the header for the DELETE button (and later EDIT button), and another table cell to contain the DELETE button.

Now the DELETE button is a hyperlink using 'ng-click="del(product.id)"', this is calling the del function on-click and passing the current products id to the function.

Also add 2 functions to the javascript:

'$scope.del = function(id)' this creates a popup confirm window. It then uses the getSelectedIndex function to loop through the array of data and then deletes the row of data using 'splice'.

Here is how the files code should be looking now with its new lines of code highlighted.

<!doctype html>
<html ng-app="crudapp">
<head>
<meta charset="UTF-8">
<title>AngularJS and CRUD</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>

<body ng-controller="productController">

    <!-- Table to output data -->
    <table cellpadding="5" cellspacing="0" border="1">
    <thead>
            <tr>
                <th>AngularJS ID</th>
                <th>SKU CODE</th>
                <th>PRODUCT</th>
                <th>PRICE</th>
                <th>QUANTITY</th>
                <th>OPTIONS</th>
            </tr>
    </thead>
    <tbody>
            <tr ng-repeat="product in listProducts">
                <td>{{product.id = $index}}</td>
                <td>{{product.sku}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price}}</td>
                <td>{{product.quantity}}</td>
                <td>
                    <a href="#" ng-click="del(product.id)">DELETE</a>
                </td>
            </tr>
    </tbody>
    </table>

    <script type="text/javascript">

        // Define crudapp as a Angular application.
        var crudapp = angular.module('crudapp', []);

        // Application controller for the module.
        crudapp.controller('productController', function($scope){

            // Populate table with products data
            $scope.listProducts = [
                {sku:'SKU1', name:'Product Name 1', price:199, quantity: 50},
                {sku:'SKU2', name:'Product Name 2', price:220, quantity: 100},
                {sku:'SKU3', name:'Product Name 3', price:55, quantity: 25},
                {sku:'SKU4', name:'Product Name 4', price:100, quantity: 50},
                {sku:'SKU5', name:'Product Name 5', price:10, quantity: 1000}
            ];

            // Delete function
            $scope.del = function(id){
                var result = confirm('Are you sure?');
                if (result===true){ 
                    var index = getSelectedIndex(id);
                    $scope.listProducts.splice(index, 1);
                };
            };

            // Function finds unique product data based on its id
            function getSelectedIndex(id){
                for(var i=0; i<$scope.listProducts.length; i++)
                    if($scope.listProducts[i].id==id)
                        return i;
                    return -1;  
            };

        });
    </script>

</body>
</html>

Now preview the file in a browser you should be able to delete separate rows of the data from the table - see the before and after below. You will notice that the id numbers reset but this would be different if taken from a database.

Before:

angularjs and crud data binding 02

After deleting the SKU3 Product:

angularjs and crud data binding 03

4. Add a Edit button to edit individual rows of data from the table.

First we will add another hyperlink for editing the row 'ng-click="selectEdit(product.id)"', this is calling the '$scope.selectEdit' function on-click and passing the current products id which then returns the data and updates the edit form fields.

We also need to add the edit form with the header 'Product Information' this form has the following text fields: sku, name, price and quantity. Also add a save button calling the edit function - 'ng-click="edit()"'.

In the javascript we add 2 more functions:

'$scope.selectEdit(id)' this returns the selected row of data and updates the form fields using the getSelectedIndex function. '$scope.edit' updates the data from the submitted form based on the id created by AngularJS - again this would normally be a database incremental id.

Here is how the files code should be looking now with its new lines of code highlighted.

<!doctype html>
<html ng-app="crudapp">
<head>
<meta charset="UTF-8">
<title>AngularJS and CRUD</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>

<body ng-controller="productController">

    <!-- Table to output data -->
    <table cellpadding="5" cellspacing="0" border="1">
    <thead>
            <tr>
                <th>AngularJS ID</th>
                <th>SKU CODE</th>
                <th>PRODUCT</th>
                <th>PRICE</th>
                <th>QUANTITY</th>
                <th>OPTIONS</th>
            </tr>
    </thead>
    <tbody>
            <tr ng-repeat="product in listProducts">
                <td>{{product.id = $index}}</td>
                <td>{{product.sku}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price}}</td>
                <td>{{product.quantity}}</td>
                <td>
                    <a href="#" ng-click="del(product.id)">DELETE</a>
                    <a href="#" ng-click="selectEdit(product.id)">EDIT</a>
                </td>
            </tr>
    </tbody>
    </table>

    <h1>Product Information</h1>

    <form name="commentForm" method="post">
    <table cellpadding="5" cellspacing="5">
        <tr>
            <td>SKU</td>
            <td>
                <input type="text" ng-model="sku">
            </td>
        </tr>
        <tr>
            <td>Product Name</td>
            <td>
                <input type="text" ng-model="name">
            </td>
        </tr>
        <tr>
            <td>Price</td>
            <td>
                <input type="text" ng-model="price">
            </td>
        </tr>
        <tr>
            <td>Quantity</td>
            <td>
                <input type="text" ng-model="quantity">
            </td>
        </tr>
        <tr>
            <td> </td>
            <td>
                <input type="button" value="Save" ng-click="edit()">
            </td>
        </tr>
    </table>
    </form>

    <script type="text/javascript">

        // Define crudapp as a Angular application.
        var crudapp = angular.module('crudapp', []);

        // Application controller for the module.
        crudapp.controller('productController', function($scope){

            // Populate table with products data
            $scope.listProducts = [
                {sku:'SKU1', name:'Product Name 1', price:199, quantity: 50},
                {sku:'SKU2', name:'Product Name 2', price:220, quantity: 100},
                {sku:'SKU3', name:'Product Name 3', price:55, quantity: 25},
                {sku:'SKU4', name:'Product Name 4', price:100, quantity: 50},
                {sku:'SKU5', name:'Product Name 5', price:10, quantity: 1000}
            ];

            // Delete function
            $scope.del = function(id){
                var result = confirm('Are you sure?');
                if (result===true){ 
                    var index = getSelectedIndex(id);
                    $scope.listProducts.splice(index, 1);
                };
            };

            // Edit and update row function
            $scope.edit = function(){
                var index = getSelectedIndex($scope.id);
                $scope.listProducts[index].sku = $scope.sku;
                $scope.listProducts[index].name = $scope.name;
                $scope.listProducts[index].price = $scope.price;
                $scope.listProducts[index].quantity = $scope.quantity;
            };

            // Select the row of data and update the form function
            $scope.selectEdit = function(id){
                var index = getSelectedIndex(id);
                var product = $scope.listProducts[index];
                $scope.id = product.id;
                $scope.sku = product.sku;
                $scope.name = product.name;
                $scope.price = product.price;
                $scope.quantity = product.quantity;
            };

            // Function finds unique product data based on its id
            function getSelectedIndex(id){
                for(var i=0; i<$scope.listProducts.length; i++)
                    if($scope.listProducts[i].id==id)
                        return i;
                    return -1;  
            };

        });
    </script>

</body>
</html>

Now preview the file in a browser you should be able to delete separate rows of the data from the table – see the before and after below. You will notice that the id numbers reset but this would be different if database data.

angularjs and crud data binding 04

5. Place an Add button on the form which is the final part of this tutorial.

First add a new submit button to the form which calls the new add function 'ng-click="add()"'.

Now add the new javascript function '$scope.add = function(id)' which adds the forms new line of data into the array using 'push'. Once the data is added it resets the textfields on the form.

Here is the final page code with all the new lines of code highlighted.

<!doctype html>
<html ng-app="crudapp">
<head>
<meta charset="UTF-8">
<title>AngularJS and CRUD</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>

<body ng-controller="productController">

    <!-- Table to output data -->
    <table cellpadding="5" cellspacing="0" border="1">
    <thead>
            <tr>
                <th>AngularJS ID</th>
                <th>SKU CODE</th>
                <th>PRODUCT</th>
                <th>PRICE</th>
                <th>QUANTITY</th>
                <th>OPTIONS</th>
            </tr>
    </thead>
    <tbody>
            <tr ng-repeat="product in listProducts">
                <td>{{product.id = $index}}</td>
                <td>{{product.sku}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price}}</td>
                <td>{{product.quantity}}</td>
                <td>
                    <a href="#" ng-click="del(product.id)">DELETE</a>
                    <a href="#" ng-click="selectEdit(product.id)">EDIT</a>
                </td>
            </tr>
    </tbody>
    </table>

    <h1>Product Information</h1>

    <form name="commentForm" method="post">
    <table cellpadding="5" cellspacing="5">
        <tr>
            <td>SKU</td>
            <td>
                <input type="text" ng-model="sku">
            </td>
        </tr>
        <tr>
            <td>Product Name</td>
            <td>
                <input type="text" ng-model="name">
            </td>
        </tr>
        <tr>
            <td>Price</td>
            <td>
                <input type="text" ng-model="price">
            </td>
        </tr>
        <tr>
            <td>Quantity</td>
            <td>
                <input type="text" ng-model="quantity">
            </td>
        </tr>
        <tr>
            <td> </td>
            <td>
                <input type="button" value="Add" ng-click="add()">
                <input type="button" value="Save" ng-click="edit()">
            </td>
        </tr>
    </table>
    </form>

    <script type="text/javascript">

        // Define crudapp as a Angular application.
        var crudapp = angular.module('crudapp', []);

        // Application controller for the module.
        crudapp.controller('productController', function($scope){

            // Populate table with products data
            $scope.listProducts = [
                {sku:'SKU1', name:'Product Name 1', price:199, quantity: 50},
                {sku:'SKU2', name:'Product Name 2', price:220, quantity: 100},
                {sku:'SKU3', name:'Product Name 3', price:55, quantity: 25},
                {sku:'SKU4', name:'Product Name 4', price:100, quantity: 50},
                {sku:'SKU5', name:'Product Name 5', price:10, quantity: 1000}
            ];

            <!-- Delete function -->
            $scope.del = function(id){
                var result = confirm('Are you sure?');
                if (result===true){ 
                    var index = getSelectedIndex(id);
                    $scope.listProducts.splice(index, 1);
                };
            };

            // Edit and update row function
            $scope.edit = function(){
                var index = getSelectedIndex($scope.id);
                $scope.listProducts[index].sku = $scope.sku;
                $scope.listProducts[index].name = $scope.name;
                $scope.listProducts[index].price = $scope.price;
                $scope.listProducts[index].quantity = $scope.quantity;
            };

            // Select the row of data and update the form function
            $scope.selectEdit = function(id){
                var index = getSelectedIndex(id);
                var product = $scope.listProducts[index];
                $scope.id = product.id;
                $scope.sku = product.sku;
                $scope.name = product.name;
                $scope.price = product.price;
                $scope.quantity = product.quantity;
            };

            // Add a new product function
            $scope.add = function(id){
                $scope.listProducts.push({
                    sku:$scope.sku, 
                    name:$scope.name, 
                    price:$scope.price, 
                    quantity:$scope.quantity    
                });
                <!-- Resets the form -->
                $scope.sku = '';
                $scope.name = '';
                $scope.price = '';
                $scope.quantity = '';
            };

            // Function finds unique product data based on its id
            function getSelectedIndex(id){
                for(var i=0; i<$scope.listProducts.length; i++)
                    if($scope.listProducts[i].id==id)
                        return i;
                    return -1;  
            };

        });
    </script>

</body>
</html>

Now preview the file in a browser you should be able to fill in the form and see the results appended to the end of the table of results.

Before submitting in the form:

angularjs and crud data binding 05

After adding the row to the table then automatically reseting the form values:

angularjs and crud data binding 06

I hope this has been a helpful tutorial on how to get started with using AngularJS.

Posted in: < JavaScript Frameworks >
me@grafxflow avatar

me@grafxflow


I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!

Visitors also viewed these posts

3 Thoughts

  1. 01 Apr
    2016

    avatar

    Zarna

    This is nice but you should give example of this crud operation from database.
  2. 21 Nov
    2016

    avatar

    David

    thank you for the post!
  3. 26 Apr
    2018

    avatar

    me@grafxflow

    A bit late in the day 'Zarna' but I have now posted a new version using Angular 5, Laravel 5.6 and MySQL. Enjoy... The link is now at the top of the post.

Add comment

Add comment