Single Page Application Using Web API And AngularJS

Introduction

Single-Page Applications (SPAs) are the Web apps that load a single HTML page and dynamically update that page as the user interacts with the app. Why do we want to write single page apps? The main reason is that they allow us to offer a more-native-app-like experiences to the user. If you want to know more about it, why do we need a single page Application? I have found a very good answer in stackoverflow. Click here to read it.

Overview

In this article, we will use Visual Studio 2013, ASP.NET Web API 2 and AngularJS 1.x. For the back end, we will use SQL Server 2008 and to connect it to the database, we will use entity framework code first approach.

Getting Started

First, we need to create a new ASP.NET application, named MusicStore in Visual Studio 2013, as shown in following image: 



Click OK and select Web API from the template and click OK.



After creating a project, you will find the solution of MusicStore Application with some default file and folder, as shown below:



Now add AngularJS to the Application. To add AngularJS to our project, we have different approaches. If you are particular about Angular versions and features you need, you might go to the Angular website and download it.

The easiest approach is to use NuGet and Package Manager console and execute the following command: 

PM> Install-Package AngularJS.core

Once this command is executed, we can find the Angular file, as listed in the image below, in Scripts folder.



Setting Up the Database

We are going to use entity framework, so first we need to install the entity framework in our Application. To install the entity framework, we need to execute the following command in Package Manager console:

PM> Install-Package EntityFramework

After successful installation, we first need to create a model class. To add a model class, right click on the Model folder, add a class and name it Music.

  1. public class Music  
  2. {  
  3.    public int Id { getset; }  
  4.    public string Title { getset; }  
  5.    public string Singers { getset; }  
  6.    public int RunTime { getset; }  
  7.    public DateTime ReleaseDate { getset; }  
  8. }  
After adding the model class, we need to add DbContext derived class with DbSet type properties and delete and query the Music object. In Model folder, we have added a MusicDb class, shown below:
  1. public class MusicDb:DbContext  
  2. {  
  3.    public DbSet<Music> Musics { getset; }  
  4. }  
Now, open Package Manager console and enable entity framework migrations. Migration allows us to manage the schema of the database and apply the schema changes. To enable the migration, we just need to execute the following command.

PM> Enable-Migrations -ContextTypeName MusicStore.Models.MusicDb

Migration helps to create Migration folder in the project with Configuration.cs file. Inside configuration.cs, we have a seed method. We will add some default seed data for Music in that method, shown below:
  1. internal sealed class Configuration : DbMigrationsConfiguration<MusicDb>  
  2.   
  3. public Configuration()  
  4. {  
  5.     AutomaticMigrationsEnabled = true;  
  6. }  
  7.   
  8. protected override void Seed(MusicDb context)  
  9. {  
  10.     //  This method will be called after migrating to the latest version.  
  11.   
  12.     //  You can use the DbSet<T>.AddOrUpdate() helper extension method   
  13.     //  to avoid creating duplicate seed data. E.g.  
  14.     //  
  15.     context.Musics.AddOrUpdate(  
  16.       m => m.Title,  
  17.       new Music  
  18.       {  
  19.           Title = "Man Ki Mat Pe Mat Chaliyo",  
  20.           Singers = "Rahat Fateh Ali Khan",  
  21.           RunTime = 5,  
  22.           ReleaseDate = new DateTime(2016, 01, 02)  
  23.       },  
  24.        new Music  
  25.        {  
  26.            Title = "Tere Mast Mast Do Nain",  
  27.            Singers = "Shreya Ghoshal, Rahat Fateh Ali Khan",  
  28.            RunTime = 5,  
  29.            ReleaseDate = new DateTime(2016, 01, 02)  
  30.        },  
  31.        new Music  
  32.        {  
  33.            Title = "Dil Ho Gaya Shanty Flat",  
  34.            Singers = "Kishore Kumar",  
  35.            RunTime = 5,  
  36.            ReleaseDate = new DateTime(2016, 01, 02)  
  37.        },  
  38.        new Music  
  39.        {  
  40.            Title = "Humka Peeni Hai Peeni",  
  41.            Singers = "Wajid, Master Salim, Shabab Sabri",  
  42.            RunTime = 5,  
  43.            ReleaseDate = new DateTime(2016, 01, 02)  
  44.        },  
  45.        new Music  
  46.        {  
  47.            Title = "Pee Loon Hoto Ki Sargam",  
  48.            Singers = "Mohit Chauhan",  
  49.            RunTime = 5,  
  50.            ReleaseDate = new DateTime(2016, 01, 02)  
  51.        }  
  52.     );  
  53. }  
We can also enable AutoMigration to make the process of adding the new features easier.
  1. AutomaticMigrationsEnabled = true;  
With these settings in place, now we can create a database using Package Manager console by executing the following command:

PM> Update-Database

The database is ready for us and now we can build a Web API to manipulate the data.

Building The Web API

To create a Web API controller, just go to Controller folder and right click it. Click on add new scaffolding, as described in the following image. In this article, we are taking basic CRUD operations only.



After clicking, the following dialog box appears. Select Music as Model class and MusicDb is the data context and click add.



After clicking Add automatically, the CRUD operation code is generated for us.
  1. public class MusicsController : ApiController  
  2. {  
  3.     private readonly MusicDb _db = new MusicDb();  
  4.   
  5.     // GET: api/Musics  
  6.     public IQueryable<Music> GetMusics()  
  7.     {  
  8.         return _db.Musics;  
  9.     }  
  10.   
  11.     // GET: api/Musics/5  
  12.     [ResponseType(typeof(Music))]  
  13.     public IHttpActionResult GetMusic(int id)  
  14.     {  
  15.         var music = _db.Musics.Find(id);  
  16.         if (music == null)  
  17.         {  
  18.             return NotFound();  
  19.         }  
  20.   
  21.         return Ok(music);  
  22.     }  
  23.   
  24.     // PUT: api/Musics/5  
  25.     [ResponseType(typeof(void))]  
  26.     public IHttpActionResult PutMusic(int id, Music music)  
  27.     {  
  28.         if (!ModelState.IsValid)  
  29.         {  
  30.             return BadRequest(ModelState);  
  31.         }  
  32.   
  33.         if (id != music.Id)  
  34.         {  
  35.             return BadRequest();  
  36.         }  
  37.   
  38.         _db.Entry(music).State = EntityState.Modified;  
  39.   
  40.         try  
  41.         {  
  42.             _db.SaveChanges();  
  43.         }  
  44.         catch (DbUpdateConcurrencyException)  
  45.         {  
  46.          if (!MusicExists(id))  
  47.             {  
  48.                 return NotFound();  
  49.             }  
  50.          throw;  
  51.         }  
  52.   
  53.      return StatusCode(HttpStatusCode.NoContent);  
  54.     }  
  55.   
  56.     // POST: api/Musics  
  57.     [ResponseType(typeof(Music))]  
  58.     public IHttpActionResult PostMusic(Music music)  
  59.     {  
  60.         if (!ModelState.IsValid)  
  61.         {  
  62.             return BadRequest(ModelState);  
  63.         }  
  64.   
  65.         _db.Musics.Add(music);  
  66.         _db.SaveChanges();  
  67.   
  68.         return CreatedAtRoute("DefaultApi"new { id = music.Id }, music);  
  69.     }  
  70.   
  71.     // DELETE: api/Musics/5  
  72.     [ResponseType(typeof(Music))]  
  73.     public IHttpActionResult DeleteMusic(int id)  
  74.     {  
  75.         var music = _db.Musics.Find(id);  
  76.         if (music == null)  
  77.         {  
  78.             return NotFound();  
  79.         }  
  80.   
  81.         _db.Musics.Remove(music);  
  82.         _db.SaveChanges();  
  83.   
  84.         return Ok(music);  
  85.     }  
  86.   
  87.     protected override void Dispose(bool disposing)  
  88.     {  
  89.         if (disposing)  
  90.         {  
  91.             _db.Dispose();  
  92.         }  
  93.         base.Dispose(disposing);  
  94.     }  
  95.   
  96.     private bool MusicExists(int id)  
  97.     {  
  98.         return _db.Musics.Count(e => e.Id == id) > 0;  
  99.     }  
  100. }  
Now, to test if our Web API code is working or not, just run the Application and navigate to api/Musics and we can see the following result:



Now, our Web API is ready with all the functionality in place. The only task left is, we need to write some Angular and HTML code to manipulate the data in Single page Application.

Building Application and Module

A module in Angular is an abstraction that allows us to group various components to keep them isolated from the other components and the code in an Application. One of the benefits of isolation is to make Angular code easier to unit test. Various features of Angular framework are organized into different modules that we need for the Application.

To set up our Angular and HTML code, follow the following steps:

Step 1

Create a new folder in a project named MusicApp. Inside this folder, we organized the scripts and HTML. Inside the MusicApp folder, we added two more folders named Scripts and Views. Scripts will store the Angular code and the Views will store the HTML code.

Step 2

Inside the Scripts folder, we will add the Js file with the name theMusic.js with following code:
  1. (function() {  
  2.    var app = Angular.module("theMusic", []);  
  3. }());  
The Angular variable is the global Angular object. Just like the JQuery API is available through a global $ variable, Angular exposes a top-level API through Angular. In the code given above, a new module named theMusic, the second parameter, the empty array, declares dependencies for the model. Technically, this module depends on the core Angular module “ng”, but we don’t need to list it explicitly.

Step 3

Add an Index.html view and write the following code in it.
  1. <head>  
  2.     <title></title>  
  3.     <script src="../../Scripts/angular.js"></script>  
  4.     <script src="../Scripts/theMusic.js"></script>  
  5. </head>  
  6. <body>  
  7.     <div ng-app="theMusic">  
  8.           
  9.     </div>  
  10. </body>  
  11. /html>  
Notice the div element in the code, which specifies a value for ng-app directive. This will inject the theMusic app to this page.

Creating Controllers, Models, and views

Angular controllers are the objects which you use to govern the section of DOM and set up a model. Angular controllers are helpful and live as long as they are associated with DOM on display. This behavior makes controllers in Angular a little different from their counterparts in ASP.NET MVC, where the controllers process a single HTTP request and then go away.

To create a controller to show the Music list, first create a new JS file in MusicApp/Scripts file and name it as a MusicListController.js. Write the following code in it, shown below:.
  1. (function(app) {  
  2.   
  3. }  
  4. (Angular.module("theMusic")));  
This code immediately invokes the function expression to avoid creating global variables. Here, Angular.module is not used to create a new module, but it is used to take the reference of the existing module. Now, modify the code, given above, of the controller as shown below:
  1. (function(app) {  
  2.    var MusicListController = function($scope) {  
  3.       $scope.message = "Manish Kumar";  
  4.    };  
  5.    app.controller("MusicListController", MusicListController);  
  6. }(Angular.module("theMusic")));
Go to the Index view, add the the reference of MusicListController and try to display the value of message, shown below:
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2.     <head>  
  3.         <title></title>  
  4.         <script src="../../Scripts/angular.js"></script>  
  5.         <script src="../Scripts/theMusic.js"></script>  
  6.         <script src="../Scripts/MusicListController.js"></script>  
  7.     </head>  
  8.     <body>  
  9.         <div ng-app="theMusic">  
  10.             <div ng-controller="MusicListController">  
  11.                 {{message}}  
  12.             </div>  
  13.         </div>  
  14.     </body>  
  15. </html>  
Now, run the project and if it is displaying the correct value, what we initialized in the controller, it means our controller is working fine and we can proceed further for the coding. In the above case, the output will be shown below: 



So far, we did not implement any of the functionality in our Application. The key abstractions our code has demonstrated so far are:  
  • The controllers are responsible for putting together a model by augmenting the $scope variable. The controllers generally avoid any DOM manipulation directly. The controller only changes UI properties by updating the data.

  • The model object is aware of the view and the controller. The model is only responsible for holding state as well as exposing some behavior to manipulate the state.

  • The View uses the template and directives to gain an access to the model information.

Some additional abstraction is still available with Angular, including the concept of the Services. The MesucListController must use a Service to retrieve the Music information data from the Server.

Services

Services in Angular are the objects that perform specific tasks, such as communication over HTTP, managing the Browser history, performing the localization, implementing DOM compilation and many more. Services like controllers are registered in a module and managed by Angular. When a controller or other component needs to make use of Services, it asks Angular for a reference to the services by including the service as a parameter to its registered function.

Now go the MusicListController and $http service and use the Get method to get the list of the music like this:

  1. (function(app) {  
  2.     var MusicListController = function($scope, $http) {  
  3.         $http.get("/api/Musics").success(function (data) {  
  4.             $scope.musics = data;  
  5.         });  
  6.     };  
  7.     app.controller("MusicListController", MusicListController);  
  8. }(angular.module("theMusic")));  
The $http service has an API, that includes methods such as GET, POST, PUT and DELETE. These methods map to the corresponding HTTP verb of same name. Thus, the code, shown above, is sending HTTP Get request to the URL /api/Music. The return value is a promise object.

Now, our controller is ready with the list of music and we need to display the list of the music in the View to index.html and add the following code:
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3.     <title></title>  
  4.     <script src="../../Scripts/angular.js"></script>  
  5.     <link href="../../Content/Site.css" rel="stylesheet" />  
  6.     <link href="../../Content/bootstrap.css" rel="stylesheet" />  
  7.     <script src="../../Scripts/bootstrap.js"></script>  
  8.     <script src="../Scripts/theMusic.js"></script>  
  9.     <script src="../Scripts/MusicListController.js"></script>  
  10. </head>  
  11. <body>  
  12.     <div ng-app="theMusic">  
  13.         <div ng-controller="MusicListController">  
  14.             <table class="table table-bordered">  
  15.                 <thead>  
  16.                     <tr>  
  17.                         <th>Title</th>  
  18.                         <th>Singers</th>  
  19.                     </tr>  
  20.                 </thead>  
  21.                 <tbody>  
  22.                     <tr ng-repeat="music in musics">  
  23.                         <td>{{music.Title}}</td>  
  24.                         <td>{{music.Singers}}</td>  
  25.                     </tr>  
  26.                 </tbody>  
  27.             </table>  
  28.         </div>  
  29.     </div>  
  30. </body>  
  31. </html>  
Hence, we achieved our first goal of the Application to display the list of music from our database.

Routing

Routing in Angular is similar to routing in ASP.NET. Angular can take care of the preceding requirement. We just need to download some additional module and write some configuration for the Application. Execute the following command in Package Manager console to install the Angular Route.

PM> Install-Package -IncludePrerelease AngularJS.Route

Once the above command is executed properly, we can check the Scripts folder that will have Angular-route.js file. Include it to Index page and list the routing module, as dependency of the Application module (theMusic):  
  1. (function() {  
  2.    var app = Angular.module("theMusic", ["ngRoute"]);  
  3. }());  
With the ngRoute dependency present in our module, we need to write the following configuration in it, shown below:
  1. (function () {  
  2.     var app = angular.module("theMusic", ["ngRoute"]);  
  3.     var config = function ($routeProvider) {  
  4.             $routeProvider  
  5.             .when("/list",  
  6.                 { templateUrl: "/MusicApp/Views/list.html", controller: "MusicListController" })  
  7.             .when("/details/:id",  
  8.                 { templateUrl: "/MusicApp/Views/details.html", controller: "DetailsController" })  
  9.             .otherwise(  
  10.                 { redirectTo: "/list", controller: "MusicListController" });  
  11.            };  
  12.   
  13.         app.config(config);  
  14. }());  
The $routeProvider offers methods such as when and otherwise to describe the URL schema for a single page Application. Now, go to Index view and remove the entire markup and add following code:
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title></title>  
  5.   
  6.     <script src="../../Scripts/angular.js"></script>  
  7.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>  
  8.     <link href="../../Content/Site.css" rel="stylesheet" />  
  9.     <link href="../../Content/bootstrap.css" rel="stylesheet" />  
  10.     <script src="../../Scripts/bootstrap.js"></script>  
  11.     <script src="../Scripts/theMusic.js"></script>  
  12.     <script src="../Scripts/MusicListController.js"></script>  
  13.     <script src="../Scripts/DetailsController.js"></script>  
  14. </head>  
  15.     <body ng-app="theMusic">  
  16.         <h2>Music store</h2>  
  17.         <div ng-view></div>  
  18.     </body>  
  19. </html>  
The <ng-view> directive is a placeholder for Angular to insert the Current View. Now, creat a list which details the view in Views folder with the following code:

List view
  1. <div ng-controller="MusicListController">  
  2.     <table class="table table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Title</th>  
  6.                 <th>Singers</th>  
  7.                 <th>Action</th>  
  8.             </tr>  
  9.         </thead>  
  10.         <tbody>  
  11.             <tr ng-repeat="music in musics">  
  12.                 <td>{{music.Title}}</td>  
  13.                 <td>{{music.Singers}}</td>  
  14.                 <td>  
  15.                     <a href="#/details/{{music.Id}}" class="btn btn-default btn-sm">Details</a>  
  16.                     <a href="#/delete/{{music.Id}}" class="btn btn-danger btn-sm">delete</a>  
  17.                 </td>  
  18.             </tr>  
  19.         </tbody>  
  20.     </table>  
  21. </div>  
After it, we create a details controller filer named DetailsController.js, shown below: 
  1. (function (app) {  
  2.     var DetailsController = function ($scope, $http,$routeParams) {  
  3.         var id = $routeParams.id;  
  4.         $http.get("/api/Musics/" + id)  
  5.             .success(function (data) {  
  6.             $scope.music = data;  
  7.         });  
  8.     };  
  9.     app.controller("DetailsController", DetailsController);  
  10. }(angular.module("theMusic")));  
Details view that we have added named details.html  is shown below:
  1. <div ng-controller="DetailsController">  
  2.     <h3>{{music.Title}}</h3>  
  3.     <div>Sing By {{music.Singers}}</div>  
  4.     <div>Released in {{music.ReleaseDate}}</div>  
  5.     <div>{{music.RunTime}} minutes long.</div>  
  6.     <br/><br/>  
  7.   <a href="#/list/" class="btn btn-info btn-default">Back to List</a>  
  8. </div>  
Now, if we run Index.html, we will get the list of music, shown below:



When we click the details button, it will redirect to the details view and show the relative details of the music, as follows:


One thing you must have noticed here is when we click on the details button, it redirects to the details view, but the page did not refresh. We can also create a custom Music Service and use that Service in our Application. Let’s discuss how to create a Custom Service

Custom MusicService

In Angular, we can define custom controllers and modules. We can also create custom directives, services, modules and many more. For this Application, we will create a custom Service, that will be capable for MusicController Web API communication. We create a Service and our controller does not need to use $http Service directly. Go to add the MusicService.js file in Scripts folder and write the following code in it:
  1. (function(app) {  
  2.     var musicService = function($http, musicApiUrl) {  
  3.         var getAll = function() {  
  4.             return $http.get(musicApiUrl);  
  5.         };  
  6.   
  7.         var getById = function(id) {  
  8.             return $http.get(musicApiUrl + id);  
  9.         };  
  10.   
  11.         var update = function(music) {  
  12.             return $http.put(musicApiUrl + music.id, music);  
  13.         };  
  14.   
  15.         var create = function(music) {  
  16.             return $http.post(musicApiUrl, music);  
  17.         };  
  18.   
  19.         var destroy = function(id) {  
  20.             return $http.delete(musicApiUrl + id);  
  21.         };  
  22.   
  23.         return {  
  24.             getAll: getAll,  
  25.             getById: getById,  
  26.             update: update,  
  27.             create: create,  
  28.             delete: destroy  
  29.         };  
  30.     };  
  31.     app.factory("musicService", musicService);  
  32. }(angular.module("theMusic")));  
Now, we need to modify the other controllers and the model accordingly.

theMusic.Js
  1. (function () {  
  2.     var app = angular.module("theMusic", ["ngRoute"]);  
  3.     var config = function ($routeProvider) {  
  4.             $routeProvider  
  5.             .when("/list",  
  6.                 { templateUrl: "/MusicApp/Views/list.html", controller: "MusicListController" })  
  7.             .when("/details/:id",  
  8.                 { templateUrl: "/MusicApp/Views/details.html", controller: "DetailsController" })  
  9.             .otherwise(  
  10.                 { redirectTo: "/list", controller: "MusicListController" });  
  11.            };  
  12.   
  13.     app.config(config);   
  14.     app.constant("musicApiUrl""/api/musics/");  
  15. }());  
MusicListController.Js
  1. (function (app) {  
  2.     var MusicListController = function ($scope, musicService) {  
  3.         musicService  
  4.             .getAll()  
  5.             .success(function (data) {  
  6.             $scope.musics = data;  
  7.         });  
  8.     };  
  9.     app.controller("MusicListController", MusicListController);  
  10. }(angular.module("theMusic")));  
DetailsController.js
  1. (function (app) {  
  2.     var DetailsController = function ($scope, $routeParams, musicService) {  
  3.         var id = $routeParams.id;  
  4.         musicService  
  5.             .getById(id)  
  6.             .success(function (data) {  
  7.             $scope.music = data;  
  8.         });  
  9.     };  
  10.     app.controller("DetailsController", DetailsController);  
  11. }(angular.module("theMusic")));  
Now, run the Application and it will show exactlythe same result, but now our code looks modular.

Now, we are going to create more controllers to delete the Music data, to Edit the music data and to add the current music data. So far, if you have read this article carefully, you have a very clear idea of how to create those views. So, I am not going to explain more in detail and am only writing the required controller and the view code.

DeleteMusic

As I have already added delete button in the list view, we will just modify the MusicListController, List view and add the functionality in it.

MusicListController.js
  1. (function (app) {  
  2.     var MusicListController = function ($scope, musicService) {  
  3.         musicService  
  4.             .getAll()  
  5.             .success(function (data) {  
  6.                 $scope.musics = data;  
  7.             });  
  8.   
  9.         $scope.delete = function (music) {  
  10.             musicService.delete(music.Id)  
  11.                 .success(function () {  
  12.                     removeMusicById(music.Id);  
  13.                 });  
  14.         };  
  15.         var removeMusicById = function (id) {  
  16.             for (var i = 0; i < $scope.musics.length; i++) {  
  17.                 if ($scope.musics[i].Id == id) {  
  18.                     $scope.musics.splice(i, 1);  
  19.                     break;  
  20.                 }  
  21.             }  
  22.         };  
  23.     };  
  24.     app.controller("MusicListController", MusicListController);  
  25. }(angular.module("theMusic")));  
List.html
  1. <div ng-controller="MusicListController">  
  2.     <table class="table table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Title</th>  
  6.                 <th>Singers</th>  
  7.                 <th>Action</th>  
  8.             </tr>  
  9.         </thead>  
  10.         <tbody>  
  11.             <tr ng-repeat="music in musics">  
  12.                 <td>{{music.Title}}</td>  
  13.                 <td>{{music.Singers}}</td>  
  14.                 <td>  
  15.                     <a href="#/details/{{music.Id}}" class="btn btn-default btn-sm">Details</a>  
  16.                     <button class="btn btn-danger btn-sm" ng-click="delete(music)">Delete</button>  
  17.                       
  18.                 </td>  
  19.             </tr>  
  20.         </tbody>  
  21.     </table>  
  22. </div>  
Now, we have delete functionality implemented. We will now implement Edit and Insert and our job is done.

Agenda for Edit and Insert

To edit the music details, a user needs to go to details of the music and click edit to edit the music details. In a similar way, where we are showing the list of music, we will add the add button to add new music details.

First, we will create an edit view that we will use in edit and insert; both based on the editable property true and false.

Edit.html
  1. <div class="row" ng-controller="EditController">  
  2.      <div class="col-md-5">  
  3.          <form ng-show="isEditable()">  
  4.              <div class="form-group">  
  5.                  <label for="Title">Title</label>  
  6.                  <input name="Title" type="text" class="form-control" placeholder="Enter title" ng-model="edit.music.Title">  
  7.              </div>  
  8.              <div class="form-group">  
  9.                  <label for="Singers">Singers</label>  
  10.                  <input name="Singers" type="text" class="form-control" placeholder="Enter Singers" ng-model="edit.music.Singers">  
  11.              </div>  
  12.   
  13.              <div class="form-group">  
  14.                  <label for="ReleaseDate">Release Date</label>  
  15.                  <input name="ReleaseDate" type="text" class="form-control" placeholder="Enter Release Date" ng-model="edit.music.ReleaseDate">  
  16.              </div>  
  17.   
  18.              <div class="form-group">  
  19.                  <label for="RunTime">RunTime</label>  
  20.                  <input name="RunTime" type="text" class="form-control" placeholder="Enter RunTime" ng-model="edit.music.RunTime">  
  21.              </div>  
  22.              <button class="btn btn-primary" ng-click="save()">Save</button>  
  23.              <button class="btn btn-primary" ng-click="cancel()">Cancel</button>  
  24.          </form>  
  25.      </div>  
  26.  </div>  
If Editable is true means the user can try to edit the records and if it is false, it means the user can try to insert the record.

Edit Controller
  1. (function(app) {  
  2.     var EditController = function ($scope, musicService) {  
  3.   
  4.         $scope.isEditable = function () {  
  5.             return $scope.edit && $scope.edit.music;  
  6.         };  
  7.   
  8.         $scope.cancel = function() {  
  9.             $scope.edit.music = null;  
  10.         };  
  11.   
  12.         $scope.save = function () {  
  13.             if ($scope.edit.music.Id) {  
  14.                 updateMusic();  
  15.             } else {  
  16.                 createMusic();  
  17.             }  
  18.         };  
  19.         $scope.musics = [];  
  20.         var updateMusic = function() {  
  21.             musicService.update($scope.edit.music)  
  22.                     .then(function () {  
  23.                     angular.extend($scope.music, $scope.edit.music);  
  24.                     $scope.edit.music = null;  
  25.                 });  
  26.         };  
  27.   
  28.         var createMusic = function () {  
  29.             musicService.create($scope.edit.music)  
  30.                 .then(function () {  
  31.                     $scope.musics.push($scope.edit.music);  
  32.                     $scope.edit.music = null;  
  33.                 });  
  34.         };  
  35.     };  
  36.     app.controller("EditController", EditController);  
  37. }(angular.module("theMusic")));  
Now, we will modify the details of the controller by adding a few lines of code:
  1. $scope.edit = function () {  
  2.    $scope.edit.music = Angular.copy($scope.music);  
  3. };  
In the details view, just add the buttons to edit by using:
  1. <button class="btn btn-default btn-sm" ng-click="edit()">Edit Music Details</button>  
  2.   
  3. <div ng-include="'/MusicApp/Views/edit.html'"></div>  
ng-include will include the edit view to edit the record in which a user will click on Edit Music button. When you run the code, it will show the following output.
 

To add the new record in the music section, we need to modify the list controller and list view like: 

ListController will add 
 
  1. $scope.create = function () {  
  2.     $scope.edit = {  
  3.         music: {  
  4.             Title: "",  
  5.             Singers: "",  
  6.             ReleaseDate: new Date,  
  7.             RunTime: 0  
  8.         }  
  9.    };  
  10. };  
This will just create an empty music object.

List.html 
  1. <button class="btn btn-danger btn-sm" ng-click="create()">Add Now Music</button>  
  2. <div ng-include="'/MusicApp/Views/edit.html'"></div>  
When you run the app now, you can insert new music record.
 

Conclusion

In this article, we learned about the SPA (Single Page Application), using AngularJS and ASP.NET Web API. If you have any questions or comments regarding this article, please post it in the comment section of this article. I hope you like it. 

Up Next
    Ebook Download
    View all
    Learn
    View all