Click here to Skip to main content
15,868,073 members
Articles / Web Development / ASP.NET / ASP.NET4.0

ASP.NET MVC-5 CRUD Using AngularJS

Rate me:
Please Sign up or sign in to vote.
4.75/5 (9 votes)
23 Jan 2016CPOL6 min read 76.6K   10K   33   6
In this article we will get a short overview on AngularJS, then we will create a ASP.Net MVC-5 CRUD application using AngularJS(v1.4.8).

Introduction:

This article is aimed to perform CRUD operations in database using AngularJS. 

AngularJS is a Client side MVC-Based JavaScript framework. According to FAQ <html>has angle brackets(<>) thus the name came “Angular”. AngularJS uses directives like ng-app,ng-model which start with base directive 'ng' that  bring to mind “Angular”.

AngularJS is

  • Open Source
  • Supported & maintained by Google
  • Smart data-binding.
  • Use MVC design pattern.
  • Smart form validations
  • Can build Single Page Application(Supports routing).
  • Loosely coupled (Uses Dependency Injection-DI).
  • Easy to Unit testing 
  • Modular architecture
  • REST- familiar 

Code in AngularJS-

HTML
<body ng-app>
    First Name: <input type="text" ng-model="fname" /> <br />
    Last Name: <input type="text" ng-model="lname" /> <br />
    Result: {{fname +' '+ lname}}
</body>

<script src="Scripts/angular.min.js"></script>

Code in JQuery-

HTML
<body>
    First Name: <input type="text" id="txtfName" /> <br />
    Last Name: <input type="text" id="txtlName" /> <br />
    Result: <label id="lblName"></label>
</body>

<script src="Scripts/jquery-2.2.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(function () {
            $('#txtfName').keyup(function () {
                $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val());
            });

            $('#txtlName').keyup(function () {
                $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val());
            });
        });
    });
</script>

isn’t it cool? Next we will know where to found, how to install it.

Download AngularJS Library:

Go to AngularJS website and download – https://angularjs.org. Click on the Download link to download the latest version of AngularJS library. We are using v1.4.8 in this application.

Let’s get started:

Let’s open Visual Studio 2015(IDE) click : [File > New > Project] the new window will appear click on ASP.Net Web Application name the project and hit “ok” button at bottom right.

Fig:1.0Image 1

Choose empty template in next window with check MVC and click on “ok” button. It will take a while to load a sample empty project.

Fig:1.1Image 2

Now the first thing we need to do is register AngularJS.Core in this application. We need to get reference from NuGet.

Fig:1.2Image 3

To do that right click on project name and click on “Manage NuGet Packages” and in next window browse searching “Angular” and install the updated version of AngularJS.Core.

Or

click on [ Tools > NuGet Package Manager > Package Manager Console ] and write

C#
Install-Package AngularJS.Core

also we need to add jQuery library in our project. Our Installation process is done. 

Data Layer:

C#
public class GenericRepository<T> : IRepository<T> where T : class
{

    CRUD_SampleEntities context = null;
    private DbSet<T> entities = null;

    public GenericRepository(CRUD_SampleEntities context)
    {
        this.context = context;
        entities = context.Set<T>();
    }

    /// <summary>
    /// Get Data From Database
    /// <para>Use it when to retive data through a stored procedure</para>
    /// </summary>
    public IEnumerable<T> ExecuteQuery(string spQuery, object[] parameters)
    {
        using (context = new CRUD_SampleEntities())
        {
            return context.Database.SqlQuery<T>(spQuery, parameters).ToList();
        }
    }

    /// <summary>
    /// Get Single Data From Database
    /// <para>Use it when to retive single data through a stored procedure</para>
    /// </summary>
    public T ExecuteQuerySingle(string spQuery, object[] parameters)
    {
        using (context = new CRUD_SampleEntities())
        {
            return context.Database.SqlQuery<T>(spQuery, parameters).FirstOrDefault();
        }
    }

    /// <summary>
    /// Insert/Update/Delete Data To Database
    /// <para>Use it when to Insert/Update/Delete data through a stored procedure</para>
    /// </summary>
    public int ExecuteCommand(string spQuery, object[] parameters)
    {
        int result = 0;
        try
        {
            using (context = new CRUD_SampleEntities())
            {
                result = context.Database.SqlQuery<int>(spQuery, parameters).FirstOrDefault();
            }
        }
        catch { }
        return result;
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

Code Explanation:

If you are new to this design pattern overview here for more.

Interface:

C#
interface IRepository<T> : IDisposable where T : class
{
    IEnumerable<T> ExecuteQuery(string spQuery, object[] parameters);
    T ExecuteQuerySingle(string spQuery, object[] parameters);
    int ExecuteCommand(string spQuery, object[] parameters);
}

Middle Layer:

C#
public partial class CustomerService
{
    private GenericRepository<Customer> CustRepository;

    public CustomerService()
    {
        this.CustRepository = new GenericRepository<Customer>(new CRUD_SampleEntities());
    }

    public IEnumerable<Customer> GetAll(object[] parameters)
    {
        string spQuery = "[Get_Customer] {0}";
        return CustRepository.ExecuteQuery(spQuery, parameters);
    }

    public Customer GetbyID(object[] parameters)
    {
        string spQuery = "[Get_CustomerbyID] {0}";
        return CustRepository.ExecuteQuerySingle(spQuery, parameters);
    }

    public int Insert(object[] parameters)
    {
        string spQuery = "[Set_Customer] {0}, {1}";
        return CustRepository.ExecuteCommand(spQuery, parameters);
    }

    public int Update(object[] parameters)
    {
        string spQuery = "[Update_Customer] {0}, {1}, {2}";
        return CustRepository.ExecuteCommand(spQuery, parameters);
    }

    public int Delete(object[] parameters)
    {
        string spQuery = "[Delete_Customer] {0}";
        return CustRepository.ExecuteCommand(spQuery, parameters);
    }
}

Our Data Layer and Service layer is ready. For creating database, please download the database script and execute it using MS SQL Server. Lets create a MVC HomeController and generate empty view.

MVC HomeController:

Let's just put this code in your home controller i'll explain it later.

C#
public class HomeController : Controller
{
    private CustomerService objCust;
    public HomeController()
    {
        this.objCust = new CustomerService();
    }

    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    // GET: All Customer
    [HttpGet]
    public JsonResult GetAllData()
    {
        int Count = 10; IEnumerable<object> customers = null;
        try
        {
            object[] parameters = { Count };
            customers = objCust.GetAll(parameters);
        }
        catch { }
        return Json(customers.ToList(), JsonRequestBehavior.AllowGet);
    }

    // GET: Get Single Customer
    [HttpGet]
    public JsonResult GetbyID(int id)
    {
        object customer = null;
        try
        {
            object[] parameters = { id };
            customer = this.objCust.GetbyID(parameters);
        }
        catch { }
        return Json(customer, JsonRequestBehavior.AllowGet);
    }

    public ActionResult Insert()
    {
        return View();
    }

    // POST: Save New Customer
    [HttpPost]
    public JsonResult Insert(Customer model)
    {
        int result = 0; bool status = false;
        if (ModelState.IsValid)
        {
            try
            {
                object[] parameters = { model.CustName, model.CustEmail };
                result = objCust.Insert(parameters);
                if (result == 1)
                {
                    status = true;
                }
                return Json(new { success = status });
            }
            catch { }
        }
        return Json(new
        {
            success = false,
            errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
        });
    }

    public ActionResult Update()
    {
        return View();
    }

    // POST: Update Existing Customer
    [HttpPost]
    public JsonResult Update(Customer model)
    {
        int result = 0; bool status = false;
        if (ModelState.IsValid)
        {
            try
            {
                object[] parameters = { model.Id, model.CustName, model.CustEmail };
                result = objCust.Update(parameters);
                if (result == 1)
                {
                    status = true;
                }
                return Json(new { success = status });
            }
            catch { }
        }
        return Json(new
        {
            success = false,
            errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
        });
    }

    // DELETE: Delete Customer
    [HttpDelete]
    public JsonResult Delete(int id)
    {
        int result = 0; bool status = false;
        try
        {
            object[] parameters = { id };
            result = objCust.Delete(parameters);
            if (result == 1)
            {
                status = true;
            }
        }
        catch { }
        return Json(new 
        { 
            success = status        
        });
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

Code Explanation:

Let's get explained the code part by part.

Get All Records: Below code sample is to get all records from database by using our middle layer/service layer. We are returning JSON data here. The format of JSON data is easy to read, follows attribute-value pairs. Initially we are getting ten(10) records, this was planning for paging in view page.

C#
// GET: All Customer
[HttpGet]
public JsonResult GetAllData()
{
    int Count = 10; IEnumerable<object> customers = null;
    try
    {
        object[] parameters = { Count };
        customers = objCust.GetAll(parameters);
    }
    catch { }
    return Json(customers.ToList(), JsonRequestBehavior.AllowGet);
}

Notice that while we are returning the list of data we have set "JsonRequestBehavior.AllowGet". if we miss that, this error message will appear:

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. 
To allow GET requests, set JsonRequestBehavior to AllowGet.

Why use it? If you read that message carefully the answer is there. This is for security reason.

Get Single Record Details: Below code sample is to retrieve a single selected record details from database, which also returning JSON data format.

C#
// GET: Get Single Customer
[HttpGet]
public JsonResult GetbyID(int id)
{
    object customer = null;
    try
    {
        object[] parameters = { id };
        customer = this.objCust.GetbyID(parameters);
    }
    catch { }
    return Json(customer, JsonRequestBehavior.AllowGet);
}

Insert Records: Below code sample will Insert/Save record details to database, which is returning a JSON result of boolean data type. If it's true then it indicate that data inserted to database successfully.

C#
// POST: Save New Customer
[HttpPost]
public JsonResult Insert(Customer model)
{
    int result = 0; bool status = false;
    if (ModelState.IsValid)
    {
        try
        {
            object[] parameters = { model.CustName, model.CustEmail };
            result = objCust.Insert(parameters);
            if (result == 1)
            {
                status = true;
            }
            return Json(new { success = status });
        }
        catch { }
    }
    return Json(new
    {
        success = false,
        errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
    });
}

Update Records: Below code sample will update existing record details in database that is selected to update, which is also returning a JSON result of boolean data type. As previuosly If it's true then it indicate that data updated to database successfully.

C#
// POST: Update Existing Customer
[HttpPost]
public JsonResult Update(Customer model)
{
    int result = 0; bool status = false;
    if (ModelState.IsValid)
    {
        try
        {
            object[] parameters = { model.Id, model.CustName, model.CustEmail };
            result = objCust.Update(parameters);
            if (result == 1)
            {
                status = true;
            }
            return Json(new { success = status });
        }
        catch { }
    }
    return Json(new
    {
        success = false,
        errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
    });
}

Delete Records: Below code sample will delete existing record details to database that is selected to delete, which is also returning a JSON result of boolean data type. If it's true then it indicate that data deleted from database successfully.

C#
// DELETE: Delete Customer
[HttpDelete]
public JsonResult Delete(int id)
{
    int result = 0; bool status = false;
    try
    {
        object[] parameters = { id };
        result = objCust.Delete(parameters);
        if (result == 1)
        {
            status = true;
        }
    }
    catch { }
    return Json(new 
    { 
        success = status
    });
}

We are done with our MVC Controller to perform CRUD operations in database. Now let's move on to next part, the AngularJS part.

AngularJS(JavaScript) Controller:

JavaScript
angular.module('myFormApp', [])
.controller('CustomerController', function ($scope, $http, $location, $window) {
    $scope.custModel = {};
    $scope.message = '';
    $scope.result = "color-default";
    $scope.isViewLoading = false;
    $scope.ListCustomer = null;
    getallData();

    //******=========Get All Customer=========******
    function getallData() {
        //debugger;
        $http.get('/Home/GetAllData')
         .success(function (data, status, headers, config) {
             $scope.ListCustomer = data;
         })
         .error(function (data, status, headers, config) {
             $scope.message = 'Unexpected Error while loading data!!';
             $scope.result = "color-red";
             console.log($scope.message);
         });
    };

    //******=========Get Single Customer=========******
    $scope.getCustomer = function (custModel) {
        $http.get('/Home/GetbyID/' + custModel.Id)
        .success(function (data, status, headers, config) {
            //debugger;
            $scope.custModel = data;
            getallData();
            console.log(data);
        })
       .error(function (data, status, headers, config) {
           $scope.message = 'Unexpected Error while loading data!!';
           $scope.result = "color-red";
           console.log($scope.message);
       });
    };

    //******=========Save Customer=========******
    $scope.saveCustomer = function () {
        $scope.isViewLoading = true;

        $http({
            method: 'POST',
            url: '/Home/Insert',
            data: $scope.custModel
        }).success(function (data, status, headers, config) {
            if (data.success === true) {
                $scope.message = 'Form data Saved!';
                $scope.result = "color-green";
                getallData();
                $scope.custModel = {};
                console.log(data);
            }
            else {
                $scope.message = 'Form data not Saved!';
                $scope.result = "color-red";
            }
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while saving data!!' + data.errors;
            $scope.result = "color-red";
            console.log($scope.message);
        });
        getallData();
        $scope.isViewLoading = false;
    };

    //******=========Edit Customer=========******
    $scope.updateCustomer = function () {
        //debugger;
        $scope.isViewLoading = true;
        $http({
            method: 'POST',
            url: '/Home/Update',
            data: $scope.custModel
        }).success(function (data, status, headers, config) {
            if (data.success === true) {
                $scope.custModel = null;
                $scope.message = 'Form data Updated!';
                $scope.result = "color-green";
                getallData();
                console.log(data);
            }
            else {
                $scope.message = 'Form data not Updated!';
                $scope.result = "color-red";
            }
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while updating data!!' + data.errors;
            $scope.result = "color-red";
            console.log($scope.message);
        });
        $scope.isViewLoading = false;
    };

    //******=========Delete Customer=========******
    $scope.deleteCustomer = function (custModel) {
        //debugger;
        var IsConf = confirm('You are about to delete ' + custModel.CustName + '. Are you sure?');
        if (IsConf) {
            $http.delete('/Home/Delete/' + custModel.Id)
           .success(function (data, status, headers, config) {
               if (data.success === true) {
                   $scope.message = custModel.CustName + ' deleted from record!!';
                   $scope.result = "color-green";
                   getallData();
                   console.log(data);
               }
               else {
                   $scope.message = 'Error on deleting Record!';
                   $scope.result = "color-red";
               }
           })
           .error(function (data, status, headers, config) {
               $scope.message = 'Unexpected Error while deleting data!!';
               $scope.result = "color-red";
               console.log($scope.message);
           });
        }
    };
})
.config(function ($locationProvider) {
    $locationProvider.html5Mode(true);
});

Code Explanation:

$http is core AngularJS service that can communicate with the remote HTTP servers. HTTP methods that participate used to communicate:

  • $http.get: get data
  • $http.post: post new data
  • $http.put: update existing data
  • $http.delete: delete existing data

Know more about $http service here

Get All Record: Using $http.get method we are retrieving all records from database.

JavaScript
//******=========Get All Customer=========******
function getallData() {
    //debugger;
    $http.get('/Home/GetAllData')
        .success(function (data, status, headers, config) {
            $scope.ListCustomer = data;
        })
        .error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while loading data!!';
            $scope.result = "color-red";
            console.log($scope.message);
        });
};

Get Single Record: Here we are retriving existing customer records from database.The $scope.getCustomer methos is getting called while edit button is getting hit/click.

JavaScript
//******=========Get Single Customer=========******
$scope.getCustomer = function (custModel) {
    $http.get('/Home/GetbyID/' + custModel.Id)
    .success(function (data, status, headers, config) {
        //debugger;
        $scope.custModel = data;
        getallData();
        console.log(data);
    })
    .error(function (data, status, headers, config) {
        $scope.message = 'Unexpected Error while loading data!!';
        $scope.result = "color-red";
        console.log($scope.message);
    });
};

Using $http.get method we are retrieving selected customer record from database by passing the Customer ID to MVC Controller update method. In return we are getting the query data and AngularJS $scope.custModel is binding the data to input model using ng-model, we know AngularJS support Two-way Data Binding.

Know more about Two-way Data Binding here

Save Record: Here we are saving customer records.The $scope.saveCustomer methos is getting called from UI when we submitting the form with customer information by clicking the submit button. Using $http.post we are passing the customer object to our MVC controller.

JavaScript
//******=========Save Customer=========******
$scope.saveCustomer = function () {
    $scope.isViewLoading = true;

    $http({
        method: 'POST',
        url: '/Home/Insert',
        data: $scope.custModel
    }).success(function (data, status, headers, config) {
        if (data.success === true) {
            $scope.message = 'Form data Saved!';
            $scope.result = "color-green";
            getallData();
            $scope.custModel = {};
            console.log(data);
        }
        else {
            $scope.message = 'Form data not Saved!';
            $scope.result = "color-red";
        }
    }).error(function (data, status, headers, config) {
        $scope.message = 'Unexpected Error while saving data!!' + data.errors;
        $scope.result = "color-red";
        console.log($scope.message);
    });
    getallData();
    $scope.isViewLoading = false;
};

The controller is doing the rest with a retun status of saved? or Not. After successful insertion we have reload(calling getallData() method again) the data table.

Edit Record: Here we are Updating existing customer records to database.The $scope.updateCustomer methos is getting called while update button is getting hit/click. Like save record, same thing also happening here. The main different in saving and updating is the Cutomer ID. This time we are passing Customer ID with customer object which is getting from a hidden input field.

HTML
<input type="hidden" ng-model="custModel.Id" name="cid" />

Using $http.post we are passing the customer object to our MVC controller.

JavaScript
//******=========Edit Customer=========******
$scope.updateCustomer = function () {
    //debugger;
    $scope.isViewLoading = true;
    $http({
        method: 'POST',
        url: '/Home/Update',
        data: $scope.custModel
    }).success(function (data, status, headers, config) {
        if (data.success === true) {
            $scope.custModel = null;
            $scope.message = 'Form data Updated!';
            $scope.result = "color-green";
            getallData();
            console.log(data);
        }
        else {
            $scope.message = 'Form data not Updated!';
            $scope.result = "color-red";
        }
    }).error(function (data, status, headers, config) {
        $scope.errors = [];
        $scope.message = 'Unexpected Error while updating data!!' + data.errors;
        $scope.result = "color-red";
        console.log($scope.message);
    });
    $scope.isViewLoading = false;
};

The controller is doing the rest with a retun status of updated? or Not. After successfully updating we have reload(calling getallData() method again) the data table.

Delete Record: Here we are Deleting existing customer records from database.The $scope.deleteCustomer methos is getting called while delete button is getting hit/click.

JavaScript
//******=========Delete Customer=========******
$scope.deleteCustomer = function (custModel) {
    //debugger;
    var IsConf = confirm('You are about to delete ' + custModel.CustName + '. Are you sure?');
    if (IsConf) {
        $http.delete('/Home/Delete/' + custModel.Id)
        .success(function (data, status, headers, config) {
            if (data.success === true) {
                $scope.message = custModel.CustName + ' deleted from record!!';
                $scope.result = "color-red";
                getallData();
                console.log(data);
            }
            else {
                $scope.message = 'Error on deleting Record!';
                $scope.result = "color-red";
            }
        })
        .error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while deleting data!!';
            $scope.result = "color-red";
            console.log($scope.message);
        });
    }
};

Let's get into UI/View section. Here's the Index view where we perform CRUD operations graphically.

Html View:

HTML
@{
    ViewBag.Title = "Index";
}

<h2>Create Customer</h2>

<div id="content" ng-controller="CustomerController">
    <span ng-show="isViewLoading" class="viewLoading">
        <img src="~/Content/images/ng-loader.gif" /> loading...
    </span>
    <div ng-class="result">{{message}}</div>
    <hr />
    <form name="frmCustomer" novalidate>
        <div>
            <input type="hidden" ng-model="custModel.Id" name="cid" />
        </div>
        <div>
            <label for="email">Customer Name</label>
            <input type="text" ng-model="custModel.CustName" name="cname" placeholder="" required ng-minlength="4" ng-maxlength="14" />
            <span class="error" ng-show="(frmCustomer.$dirty||submitted) && frmCustomer.cname.$error.required">Customer name is Required</span>
            <span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.minlength">Minimum length required is 5</span>
            <span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.maxlength">Minimum length required is 15</span>
        </div>
        <div>
            <label for="email">E-mail address</label>
            <input type="email" ng-model="custModel.CustEmail" name="email" placeholder="" required />
            <span class="error" ng-show="(frmCustomer.$dirty ||submitted) && frmCustomer.email.$error.required">EmailId is Required!</span>
            <span class="error" ng-show="(frmCustomer.$dirty ||submitted) && frmCustomer.$error.email">Invalid EmailId!</span>
        </div>
        <div class="btn">
            <input type="submit" value="Save" ng-click="saveCustomer()" ng-disabled="frmCustomer.$invalid">
            <input type="submit" value="Update" ng-click="updateCustomer()" ng-disabled="frmCustomer.$invalid">
        </div>
    </form>
    <hr />

    <h2>All Customers</h2>
    <table class="table table-striped">
        <tr ng-repeat="custModel in ListCustomer">
            <td>{{custModel.Id}}</td>
            <td>{{custModel.CustName}}</td>
            <td>{{custModel.CustEmail}}</td>
            <td>
                <a href="#" ng-click="getCustomer(custModel)" title="Edit Record">
                    <img src="~/Content/images/edit.png" />
                </a><a href="#" ng-click="deleteCustomer(custModel)" title="Delete Record">
                    <img src="~/Content/images/erase.png" />
                </a>
            </td>
        </tr>
    </table>
</div>

@section JavaScript{
    <script src="~/Scripts/angular.js"></script>
    <script src="~/ScriptsNg/CustomerController.js"></script>
}

Code Explanation:

Below code sample is a table with repeating table row(<tr>). Here ng-repeat is diplaying single record(custModel ) with it's template once per record from ListCustomer, or simply working as a repeater of table row.

Know more about ng-repeat here

HTML
<table class="table table-striped">
    <tr ng-repeat="custModel in ListCustomer">
        <td>{{custModel.Id}}</td>
        <td>{{custModel.CustName}}</td>
        <td>{{custModel.CustEmail}}</td>
        <td>
            <a href="#" ng-click="getCustomer(custModel)" title="Edit Record">
                <img src="~/Content/images/edit.png" />
            </a><a href="#" ng-click="deleteCustomer(custModel)" title="Delete Record">
                <img src="~/Content/images/erase.png" />
            </a>
        </td>
    </tr>
</table>

We are almost done. Let's style our UI with CSS, below is css that we used to style the UI.

Form Style:

CSS
#content label {
    width: 150px;
}

.btn {
    margin-left: 140px;
}

#content input[type=submit] {
    width: 85px;
    padding: 5px 15px;
    background: #ff6a00;
    border: 0 none;
    cursor: pointer;
    color: #fff;
}

.error {
    color: red;
}

.color-default {
    color: #000;
}

.color-red {
    color: red;
}

.color-green {
    color: green;
}

#content input.ng-dirty.ng-invalid {
    border: 1px solid red;
    background-color: rgb(255, 244, 244);
}

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;
}

Hide Html Flash(ng-cloak):

While loading our page you may noticed that Angular html template are visible/flash. It is happen while the browser in its compilation process of Angular html template, usually it flash while the page is loading. Which can hide using "ng-cloak/data-ng-cloak" directive.

Know more about ng-cloak here

We also need to add css class in our application start point.

HTML
<body ng-app="myFormApp" class="ng-cloak">

below is the css class of using ng-cloak.

CSS
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;
}

Let’s put a breakpoint on Updater() method in HomeController and run it, after submitting the form it’ll hits the breakpoint.

Fig:1.3Image 4

In debug mode we can see the model is populated with form data. We can also debug using browser by putting debugger in our script.

JavaScript
$scope.updateCustomer = function () {
  debugger;
};

Fig:1.4Image 5

In debug mode in our browser we can see the $scope.custModel is populated with form data,which is going to update the selected record in database.

Finally Output:

Image 6

[Go to Browser: Inspect > Console]

Image 7

[Browser: Inspect > Network]

Image 8

Hope that this will help you to make a way of learning AngularJS. Happy ending :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) s3 Innovate Pte Ltd
Bangladesh Bangladesh
Hi, I am Shashangka Shekhar,

Working with Microsoft Technologies. Since March 2011, it was my first step to working with Microsoft Technologies, achieved bachelor’s degree on Computer Science from State University of Bangladesh(Dhaka). Have 12+ years of professional experience, currently working as Technical Lead at Surbana Jurong Private Limited.

I believe in desire of learning & also love to be a part of .Net Community by sharing knowledge’s.

Comments and Discussions

 
QuestionHow to add another Controller Pin
Connect Rohit Kumar29-Apr-18 9:39
Connect Rohit Kumar29-Apr-18 9:39 
PraiseNice Article Pin
er-sandeep3-Mar-18 19:24
er-sandeep3-Mar-18 19:24 
Question[My vote of 1] Wont work Pin
Member 134525049-Oct-17 8:53
Member 134525049-Oct-17 8:53 
AnswerRe: [My vote of 1] Wont work Pin
Shashangka Shekhar12-Oct-17 18:53
professionalShashangka Shekhar12-Oct-17 18:53 
Questionall customers data is not updated Pin
kavety pavan kumar2-Feb-17 16:26
kavety pavan kumar2-Feb-17 16:26 
AnswerRe: all customers data is not updated Pin
wiliishaha29-Sep-17 4:16
wiliishaha29-Sep-17 4:16 
This is true. How to solve this?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.