Angular JS is a JavaScript framework to create SPA (Single Page Application). It is a client side MV* (MVC+MVVM=MV*) framework. Angular JS extends HTML by providing Directives that add functionality to your markup and that allow you to create powerful dynamic templates for application.

Below are some Angular JS directives which I have used in sample application.

ng-app : It is entry point of AngularJs to the page. It shows that the application is angular js app.

ng-controller :It is directive to define the controller. It attaches a controller class to the view.

ng-repeat :It creates loop in your page like foreach loop.

angular.module : It is use to create, register and retrieve all angular module.

$http : It is an XMLHttpRequest object for requesting external data.

$http.get : It read the json data. it takes two parameter url and config  but config is optional.

In this article I am going to show a basic example to use Angular JS. I will show you how to create a basic application in MVC4 with Angular JS.

 

Step 1

Start Visual Studio 2013 or 2012

Create a new project -> Web -> Visual Studio 2012

Select Asp.Net MVC4 Web Application

Provide the Name and Location for the project and Click Next

Choose Basic template as project template and Click Ok

Step 2

Create a DataBaseContext class inside Model folder for database factory (insert, update, delete or select the data in database). You can create database and table manually or if you use my approach it will create database and table automatically when you run the application first time because of I have used here Code First approach.

DatabaseContext.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace AngularJSWithMVC.Models
{
    public class DatabaseContext:DbContext
    {
        public DatabaseContext()
            : base("DefaultConnection")
        {
        }
        public DbSet<EmployeeModel> EmployeeModels { get; set; }
    }
}

Create one another entity class EmployeeModel.cs 

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AngularJSWithMVC.Models
{
    public class EmployeeModel
    {
        [Key]
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Address { get; set; }
        public string EmailId { get; set; }
    }
}

Web.Config connection string to access database.

<connectionStrings>
    <add name="DefaultConnection"  connectionString="Data Source=(local);DataBase=demodb;user id=sa; password=xyz;" providerName="System.Data.SqlClient" />
  </connectionStrings>

And now a controller to show the data on View

using AngularJSWithMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AngularJSWithMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            
            return View();
        }

        public JsonResult GetAllEmployee()
        {
            using (DatabaseContext db = new DatabaseContext())
            {
                var employeeList = db.EmployeeModels.ToList();
                return Json(employeeList,JsonRequestBehavior.AllowGet);
            }
        }
    }
}
Step 3

Now times to setup Angular JS Module, Service and Controller. So, create a folder with name “AngularScripts” inside the Content folder for clean code.

AppModule.js

Inside AngularScripts folder create a AppModule.js file when you manage you module setting and give it a name as I have given “AngularApp”.

var app = angular.module("AngularApp", []);

Service.js

Create another javascript file “Service.js” for fetching the data from database and provide it to controller. You have to provide a name of the service like “EmployeeService”. Here I am getting the json data from database using GetAllEmployee which will return JsonResult from the EmployeeController.

app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        debugger;
        return $http.get("/employee/getallemployee");
    };
});

Controller.js

Last but you have to create another javascript file to “Controller.js” which will use to show the data on View. Here also you have to provide a unique name for the controller as I have used “EmpCtrl”.

app.controller("EmpCtrl", function ($scope, EmployeeService) {

    GetAllEmployee();

    function GetAllEmployee() {

        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (emp) {
            $scope.employees = emp.data;
        }, function () {
            alert('Data not found');
        });
    }
});
Step 4

Now time to show the data on View but before that I have to setup angular js component and setting on Layout file. Like add all js component which I have created before Service.js, Controller.js etc. Below you can see First of all I have used ng-app that will denoted that It is an angular app and you have to provide the name of app which is already defined in “AngularApp.js”.

I have also used CDN file to use angular feature.

https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js

Layout.cshtml

<!DOCTYPE html>
<html ng-app="AngularApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
    <script src="~/Content/AngularScripts/AppModule.js"></script>
    <script src="~/Content/AngularScripts/Service.js"></script>
    <script src="~/Content/AngularScripts/Controller.js"></script>
            @Styles.Render("~/Content/css")
    </head>           
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Create a view for EmployeeController’s Index method and add below code.

Index.cs

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div ng-controller="EmpCtrl">
    <div>
        <h2 align="center">Angular JS Basic Example</h2>
        <h5 align="center">Employee List</h5>
        <table border="1" cellpadding="10" align="center">
            <tr>
                <td>
                    Employee Id
                </td>
                <td>
                    Employee Name
                </td>
                <td>
                    Address
                </td>
                <td>
                    Email Id
                </td>
            </tr>
            <tr ng-repeat="emp in employees">
                <td>
                    {{emp.EmployteeId}}
                </td>
                <td>
                    {{emp.EmployeeName}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                    {{emp.EmailId}}
                </td>
            </tr>
        </table>
    </div>
</div>
Conclusion:

So, today we learned how to create a first and very basic application in Angular JS with MVC that show the data from database. We also learn some Angular directives and how and where to use it.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks