What is AngularJS?
AngularJS is a JavaScript MVC framework developed by Google that lets you build well structured, easily testable and maintainable front-end applications, in other words we can say that AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications (here is a very good article that may clear up doubts related to the SPA and the Single Page Myth). Its goal is to augment browser-based applications with Model–View–Controller capability, in an effort to make both development and testing easier.
You can also refer to Angular JS Introduction for more clarifications.
Why Angular JS?
HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web applications. AngularJS lets you extend your HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable and quick to develop, if you not used Angular JS yet then you have really missed out.
So the question is, are there already many other JavaScript frameworks available that makes a difference in Angular JS. Actually other frameworks deal with HTML's shortcomings by abstracting away HTML, CSS and/or JavaScript or by providing an imperative way for manipulating the DOM. Neither of these address the root problem that HTML was not designed for dynamic views.
Why I like this framework the most is its extensibility feature that makes it fully extensible and that works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs.
There are many other features that provide you a different experience of development that you may not have experienced before.
Here is the simple CRUD application made using AngularJS, MVC5 and Web API
Now add a new model class in the model directory :
Friend.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace AngularJSWebApplication1.Models
{
public class Friend
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int FriendId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Notes { get; set; }
}
}
Now add a context class:
FriendsContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AngularJSWebApplication1.Models
{
public class FriendsContext : DbContext
{
public FriendsContext() : base("name=DefaultConnection")
{
base.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Friend> Friends { get; set; }
}
}
Now add a controller in the controller directory:
FriendController.cs
using AngularJSWebApplication1.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace AngularJSWebApplication1.Controllers
{
public class FriendController : ApiController
{
private FriendsContext db = new FriendsContext();
// GET api/<controller>
[HttpGet]
public List<Friend> Get()
{
return db.Friends.ToList();
}
// GET api/<controller>/5
public Friend Get(int id)
{
int RequestPerSecond = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RequestPerSecond"] ?? "1");
Friend friend = db.Friends.Find(id);
if (friend == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return friend;
}
// POST api/<controller>
public HttpResponseMessage Post(Friend friend)
{
if (ModelState.IsValid)
{
db.Friends.Add(friend);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, friend);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = friend.FriendId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// PUT api/<controller>/5
public HttpResponseMessage Put(Friend friend)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
/*if (id != friend.FriendId)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}*/
db.Entry(friend).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// DELETE api/<controller>/5
public HttpResponseMessage Delete(int id)
{
Friend friend = db.Friends.Find(id);
if (friend == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Friends.Remove(friend);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, friend);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Now install AngularJS using Manage Nuget Package Manager.
Now add a new JavaScript file in the scripts directory and add angular functions as follow :
JavaScript1.js
function friendController($scope, $http) {
$scope.loading = true;
$scope.addMode = false;
//Used to display the data
$http.get('/api/Friend/').success(function (data) {
$scope.friends = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
//Used to add a new record
$scope.toggleAdd = function () {
$scope.addMode = !$scope.addMode;
};
$scope.add = function () {
$scope.loading = true;
$http.post('/api/Friend/', this.newfriend).success(function (data) {
alert("Added Successfully!!");
$scope.addMode = false;
$scope.friends.push(data);
$scope.loading = false;
}).error(function (data) {
$scope.error = "An Error has occured while Adding Friend! " + data;
$scope.loading = false;
});
};
//Used to save a record after edit
$scope.toggleEdit = function () {
this.friend.editMode = !this.friend.editMode;
};
$scope.save = function () {
//alert("Edit");
$scope.loading = true;
var frien = this.friend;
debugger;
//alert(frien);
$http.put('/api/Friend/', frien).success(function (data) {
alert("Saved Successfully!!");
frien.editMode = false;
$scope.loading = false;
}).error(function (data) {
alert("Error in edit!!");
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
//Used to delete a record
$scope.deletefriend = function () {
$scope.loading = true;
var friendid = this.friend.FriendId;
$http.delete('/api/Friend/' + friendid).success(function (data) {
alert("Deleted Successfully!!");
$.each($scope.friends, function (i) {
debugger;
if ($scope.friends[i].FriendId === friendid) {
$scope.friends.splice(i, 1);
return false;
}
});
$scope.loading = false;
}).error(function (data) {
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
}
Now open BundleConfig.cs and add it :
using System.Web;
using System.Web.Optimization;
namespace AngularJSWebApplication1
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
"~/Scripts/angular.min.js"));
bundles.Add(new ScriptBundle("~/bundles/myjs").Include(
"~/Scripts/JavaScript1.js"));
}
}
}
Now open the _Layout.cshtml page from the Shared folder and add these lines to render AngularJS and myjs in the application.
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/angularjs")
@Scripts.Render("~/bundles/myjs")
Now open the Index.cshtml, clear it and add following code :
@{
ViewBag.Title = "FriendView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Friends View</h2>
<div data-ng-app data-ng-controller="friendController" class="container">
<strong class="error">{{ error }}</strong>
<div id="mydiv" data-ng-show="loading">
<img src="Images/ajax-loader.gif" class="ajax-loader" />
</div>
<p data-ng-hide="addMode"><a data-ng-click="toggleAdd()" href="javascript:;" class="btn btn-primary">Add New</a></p>
<form name="addFriend" data-ng-show="addMode" style="width:600px;margin:0px auto;">
<label>FirstName:</label><input type="text" data-ng-model="newfriend.FirstName" required /><br />
<label>LastName:</label><input type="text" data-ng-model="newfriend.LastName" required /><br />
<label>Address:</label><input type="text" data-ng-model="newfriend.Address" required /><br />
<label>City:</label><input type="text" data-ng-model="newfriend.City" required /><br />
<label>PostalCode:</label><input type="text" data-ng-model="newfriend.PostalCode" required /><br />
<label>Country:</label><input type="text" data-ng-model="newfriend.Country" required /><br />
<label>Notes:</label><input type="text" data-ng-model="newfriend.Notes" required /><br />
<input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addFriend.$valid" class="btn btn-primary" />
<input type="button" value="Cancel" data-ng-click="toggleAdd()" class="btn btn-primary" />
<br /><br />
</form>
<div id="displaytable" style="width: 100%;height: 200px;overflow: auto;">
<table class="table table-bordered table-hover" style="width:800px">
<tr>
<th>#</th>
<td>FirstName</td>
<th>LastName</th>
<th>Address</th>
<th>City</th>
<th>PostalCode</th>
<th>Country</th>
<th>Notes</th>
<th>Operations</th>
</tr>
<tr data-ng-repeat="friend in friends">
<td><strong data-ng-hide="friend.editMode">{{ friend.FriendId }}</strong></td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.FirstName }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.FirstName" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.LastName }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.LastName" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.Address }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Address" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.City }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.City" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.PostalCode }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.PostalCode" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.Country }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Country" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.Notes }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Notes" />
</td>
<td>
<p data-ng-hide="friend.editMode"><a data-ng-click="toggleEdit(friend)" href="javascript:;">Edit</a> | <a data-ng-click="deletefriend(friend)" href="javascript:;">Delete</a></p>
<p data-ng-show="friend.editMode"><a data-ng-click="save(friend)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(friend)" href="javascript:;">Cancel</a></p>
</td>
</tr>
</table>
</div>
<hr />
</div>
<script>
$(document).ready(function () { $('#displaytable').jScrollPane(); })
</script>
Done !!!
No comments:
Post a Comment