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
Posted Comments :
Mukesh Kumar Author Posted : 9 Years Ago
@Vashudha, Thanks for your valuable comment on this articles. I am grateful that you took the time to write this comment to motivate me.
dinesh Posted : 9 Years Ago
Iam not getting output
kaalyan Posted : 9 Years Ago
bhayya i'have got the output however the thing is u said that this is a code approach as well will creates automatically a db and tbl this has not done , ofcourse i created them manually and am unable to retrieve the data from database could u please look into this so that i will mail u soon,
Deepthee Posted : 9 Years Ago
I am not getting output instead it showing {emp.{EmployeeName}} i have created the db and the table before only and enetered data in the table too. after that i followed the above steps to fetch the data from the db but i am not able to get it. can you please suggest me how to get the output. its little bit urgent
May Posted : 9 Years Ago
Thank you. It is very useful for me.
Jaime Posted : 9 Years Ago
Great post. Check this one out as well. AngularJS - When JavaScript Met MVC https://www.ziptask.com/AngularJS-When-JavaScript-Met-MVC
webdeveloper Posted : 8 Years Ago
in file route.config in folder app_start wirte : defaults: new { controller = "EmployeeController", action = "getallemployee", id = UrlParameter.Optional }
Hemant Posted : 8 Years Ago
Thank you, it is useful to me
Animesh chatterjee Posted : 8 Years Ago
Can you please give me this example without using Linq or Code first approach. Please give me this example by stored procedure and normal ado.net like dataset to retirve value from table
Asifa.M Posted : 8 Years Ago
Very useful
Sibadata Nayak Posted : 8 Years Ago
The example is fine but while updating the connection string in web.config it give below error. An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code Additional information: The model backing the 'DatabaseContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
waleed Posted : 8 Years Ago
can anyone please provide me the visual studio project for this tutorial , it might be helpful for me after going to this tutorial....
Jayaraj B Posted : 8 Years Ago
this sample code very useful and easy to learn angular js
Richa Posted : 8 Years Ago
fine & precise article but I have one doubt that according to this for each view , we need to create a separate controller which will increase the no. of files unnecessary so can I use one controller for multiple views.
Gandy's dog Posted : 8 Years Ago
Very basic crap - useless in real life
Vijay Posted : 8 Years Ago
Searching for it... Thanks. http://www.aspmantra.com
Mukund Posted : 7 Years Ago
Please save data into database with one dropdownList and radio button List using angularJs in mvc.
Niaz Posted : 7 Years Ago
It turns out an error that Data not found
Vasudha Posted : 9 Years Ago
Nice article. Simple and precise.