AngularJS Filter, Sorting and Animation Using MVC and WCF Rest

Introduction



You can also view my previous articles related to AngularJs using MVC and the WCF Rest Serice.

This article will explain in detail how to create an AngularJS Filter, Sort and Simple Animation using  WCF Rest Service.
  1. How to create a WCF Rest service and retrieve data from a database.
  2. How to install the AngularJS Package into a MVC application.
  3. How to create our AngularJS application to create our own Master Detail Grid.
  4. How to use a WCS service in AngularJS to use Filter, Sort and Animation.
Note: The prerequisites are Visual Studio 2013 (if you don't have Visual Studio 2013, you can download it from the Microsoft website).

Here we can see some basics and reference links for Windows Communication Foundation (WCF). WCF is a framework for building service-oriented applications.

Service-oriented application

Using a protocol the service can be shared and used over a network.

For example, let's consider we are now working on a project and we need to create a common database function and those functions need to be used in multiple projects and the projects are in a different place and connected by the internet.

In this case we can create a WCF service and we can write all our common database functions in our WCF service class. We can deploy our WCF in IIS and use the URL in our application to do database functions. In the code part let's see how to create a WCF REST service and use it in our AngularJS application.

If you are interested in reading more about WCF then kindly go through this link.
https://msdn.microsoft.com/en-in/library/dd203052.aspx

AngularJS

We might be be familiar with what the Model, View, View Model (MVVM) and what Model, View and Controller (MVC) are. AngularJS is a JavaScript framework that is purely based on HTML, CSS and JavaScript.

The AngularJS Model View Whatever (MVW) pattern is similar to the MVC and MVVM patterns. In our example I have used Model, View and Service. In the code part let's see how to install and create AngularJS in our MVC application.

Since this article explains how to use Filter, Sort and Simple Animation in AngularJS let's see one by one here.

ng-repeat: First we start with ng-repeat. This can be used to display the array of data one by one within our Table td or within a List, for example let's consider we want to display the data from 1 to 10. Usualy we do a loop and display the value one by one or we add values from 1 to 10 to an array and display using a loop.To use looping and display the data one by one in AngularJs we use ng-repeat.

For example let's see the preceding case to display the data from 1 to 10 in a table so the code will be like this.
  1. <table>  
  2.     <tbody ng-repeat="Numbers in [1, 2, 3, 4,5,6,7,8,9,10] ">  
  3.         <tr>  
  4.             <td>  
  5.                 {{Numbers}}  
  6.             </td>  
  7.         </tr>  
  8.     </tbody>  
  9. </table> 
The example can be used to display the names one by one from the name Array.
  1. <table>  
  2.     <tbody ng-repeat="Names in ['Shanu','Afraz','Raja','Afreen','Mak','Albert'] ">  
  3.         <tr>  
  4.             <td>  
  5.                 {{Names}}  
  6.             </td>  
  7.         </tr>  
  8.     </tbody>  
  9. </table>
To test this example we need to add our angular.js to our root folder.

The complete code will be like this.

Here we can see that first we have added the angular.js reference.
  1. <html ng-app="MyAngularModule" xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4. <script src="http://code.angularjs.org/1.2.2/angular.js"></script>  
  5. <script>  
  6.         angular.module('MyAngularModule', [])  
  7.         .controller('myAngularController', function (  
  8.           $scope  
  9.         ) {  
  10.         });  
  11.     </script>  
  12. </head>  
  13. <body ng-controller="myAngularController">  
  14.     <table>  
  15.         <tbody ng-repeat="Numbers in [1, 2, 3, 4,5,6,7,8,9,10] ">  
  16.             <tr>  
  17.                 <td>  
  18.                     {{Numbers}}  
  19.                 </td>  
  20.             </tr>  
  21.         </tbody>  
  22.     </table>  
  23.     <table>  
  24.         <tbody ng-repeat="Names in ['Shanu','Afraz','Raja','Afreen','Mak','Albert'] ">  
  25.             <tr>  
  26.                 <td>  
  27.                     {{Names}}  
  28.                 </td>  
  29.             </tr>  
  30.         </tbody>  
  31.     </table>  
  32. </body>  
  33. </html> 
  • Filter
The filters can be added with the ng-repeat using the pipe symbol, for example let's consider the preceding example.
For example we can consider the preceding example where we display the names of the array using the ng-repeat. Now we can add the filter for the preceding example.

Here we can see with ng-repeat we have added the filter and for the filter we have given the TextBox Model id. When the user presses the key on the TextBox the filter will be applied for the loop and display the appropriate value as in the following:
  1. ng-repeat="Names in ['Shanu','Afraz','Raja','Afreen','Mak','Albert'] | filter:myNameFilters  
Complete Code
  1. <html ng-app="MyAngularModule" xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script src="http://code.angularjs.org/1.2.2/angular.js"></script>  
  5.     <script>  
  6.         angular.module('MyAngularModule', [])  
  7.         .controller('myAngularController'function (  
  8.           $scope  
  9.         ) {  
  10.         });  
  11.     </script>  
  12. </head>  
  13. <body ng-controller="myAngularController">  
  14.     Filter By NAme : <input type="text" ng-model="myNameFilters">  
  15.     <table border=1>  
  16.         <tbody ng-repeat="Names in ['Shanu','Afraz','Raja','Afreen','Mak','Albert']  | filter:myNameFilters ">  
  17.             <tr>  
  18.                 <td>  
  19.                     {{Names}}  
  20.                 </td>  
  21.             </tr>  
  22.         </tbody>  
  23.     </table>  
  24. </body>  
  25. </html> 
  • Sort
The same as for a filter we add the orderBy with field and reverse value in ng-repat using the pipe symbol.
The OrderBy can be added with the ng-repeat using the pipe symbol, for example let's consider the preceding example.
Where we have displayed the names of the array using the ng-repeat. Now we can add the filter for the preceding example.

Here in the first Tr and Td, I display the Table Heading and in the click event I display the order by names in ascending and descending order.
  1. ng-repeat="nme in Names | filter:myNameFilters | orderBy:predicate:reverse 
Complete Code
  1. <html ng-app="MyAngularModule" xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script src="http://code.angularjs.org/1.2.2/angular.js"></script>  
  5.       <script>  
  6.         angular.module('MyAngularModule', [])  
  7.         .controller('myAngularController', function (  
  8.           $scope  
  9.         ) {  
  10.           });  
  11.     </script>  
  12. </head>  
  13. <body ng-controller="myAngularController" ng-init="Names = [{name:'Shanu'},  
  14.                        {name:'Afraz'},  
  15.                         {name:'Afreen'},  
  16.                          {name:'Vijay'},  
  17.                          {name:'Mak'},  
  18.                         {name:'Raja'}]">  
  19.       Filter By NAme : <input type="text" ng-model="myNameFilters">  
  20.     <table border=1>  
  21.         <tr>  
  22.             <td ng-click="predicate = 'name'; reverse=!reverse">  
  23.                 <b>Toy Code</b>  
  24.             </td>  
  25.         </tr>  
  26.         <tbody ng-repeat="nme in Names   | filter:myNameFilters  | orderBy:predicate:reverse">  
  27.               <tr>  
  28.                 <td>  
  29.                     {{nme.name}}  
  30.                 </td>  
  31.             </tr>  
  32.         </tbody>  
  33.     </table>  
  34. </body>  
  35. </html> 
  • Animation
For using the Animation in AngularJs we must include “angular-animate.min.js” and in the module we my must pass the parameter “ngAnimate”
The code will look as in this:
  1. Add the refreance:
    1. <script src="http://code.angularjs.org/1.2.2/angular-animate.min.js"></script> 
  2. Pass the parameter in Module as "ngAnimate":
    1. angular.module('MyAngularModule', ['ngAnimate']) 
  3. Add your animation CSS to your HTML page. Here in my example I will be get a fade In and out of the display of the text that is binding using ng-repeat.
Complete Code
  1. <html ng-app="MyAngularModule" xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script src="http://code.angularjs.org/1.2.2/angular.js"></script>  
  5.     <script src="http://code.angularjs.org/1.2.2/angular-animate.min.js"></script>  
  6.     <style>  
  7.         .ng-enter
  8.          {  
  9.             -webkit-transition: 1s;  
  10.             transition: 3s;  
  11.             opacity: 0;  
  12.         }  
  13.           .ng-enter-active
  14.        {  
  15.             opacity: 1;  
  16.         }  
  17.           .ng-leave
  18.        {  
  19.             -webkit-transition: 1s;  
  20.             transition: 2s;  
  21.         }  
  22.           .ng-leave-active {  
  23.             opacity: 0;  
  24.         }  
  25.     </style>  
  26.     <script>  
  27.         angular.module('MyAngularModule', ['ngAnimate'])  
  28.         .controller('myAngularController'function (  
  29.           $scope  
  30.         ) {  
  31.         });  
  32.     </script>  
  33. </head>  
  34. <body ng-controller="myAngularController" ng-init="Names = [{name:'Shanu'},  
  35.                        {name:'Afraz'},  
  36.                         {name:'Afreen'},  
  37.                          {name:'Vijay'},  
  38.                          {name:'Mak'},  
  39.                         {name:'Raja'}]">  
  40.       Filter By NAme : <input type="text" ng-model="myNameFilters">  
  41.     <table border=1>  
  42.         <tr>  
  43.             <td ng-click="predicate = 'name'; reverse=!reverse">  
  44.                 <b>Toy Code</b>  
  45.             </td>  
  46.         </tr>  
  47.         <tbody ng-repeat="nme in Names   | filter:myNameFilters  | orderBy:predicate:reverse">  
  48.               <tr>  
  49.                 <td>  
  50.                     {{nme.name}}  
  51.                 </td>  
  52.             </tr>  
  53.         </tbody>  
  54.     </table>  
  55. </body>  
  56. </html> 
Reference links:
http://www.w3schools.com/angular/default.asp
https://docs.angularjs.org/api/ng/filter/filter

These are a few simple examples using HTML. Now let's see in detail how to implement this in our MVC application using a WCF rest service.

Code Part
  • Create Database and Table
We will create a ToysDetails table under the Database ToysDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2012.
The following is a script to create a database, table and a sample to insert data:
  1. USE MASTER  
  2. GO 
The following checks whether a database exists. If the database exists then drop it and create a new database.
  1. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'ToysDB' ) 

  2. DROP DATABASE ToysDB  
  3. GO  
  4.   
  5. CREATE DATABASE ToysDB  
  6. GO  
  7.   
  8. USE ToysDB  
  9. GO 
  • ToysDetails table
The following creates the Table ToysDetails. This table will be used to store the details like Toys Information.
  1. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'ToysDetails' )  
  2. DROP TABLE Professional_Type  
  3. GO  
  4.   
  5. CREATE TABLE ToysDetails  
  6. (  
  7. Toy_ID VARCHAR(20) NOT NULL,  
  8. Toy_Name VARCHAR(100) NOT NULL,  
  9. Toy_Price int NOT NULL,  
  10. Image_Name VARCHAR(100) NOT NULL,  
  11. Item_Date DateTime NOT NULL,  
  12. AddedBy VARCHAR(100) NOT NULL,  
  13. CONSTRAINT [PK_ToysDetails] PRIMARY KEY CLUSTERED  
  14. (  
  15. [Toy_ID] ASC  
  16. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  17. ON [PRIMARY]  
  18.   
  19. GO 
Use the following to insert the sample records into the ToysDetails table.
  1. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy001','Abacus',250,'Abacus.png',getdate(),'Shanu')  
  2. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy002','Babel Fish',350,'Babelfish.png',getdate()-10,'Afraz')  
  3. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy003','Base Ball',1400,'Baseball.png',getdate()-24,'Shanu')  
  4. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy004','Basket Ball',1390,'BasketballBall.png',getdate()-36,'Raj')  
  5. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy005','Blue Fish',450,'BlueFish.png',getdate()-90,'Afraz')  
  6. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy006','Brown Bear',1250,'BrownBear.png',getdate()-34,'Mak')  
  7. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy007','CabrioletRed Car',950,'CabrioletRed.png',getdate()-20,'Albert')  
  8. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy008','Chevelot Car',1150,'Chevelot.png',getdate()-26,'Gowri')  
  9. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy009','Duck',399,'Duck.png',getdate()-44,'Afraz')  
  10. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy010','FireEscape Van',897,'FireEscape.png',getdate()-12,'Shanu')  
  11. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy011','Mini Car',750,'MiniCar.png',getdate(),'Shanu')  
  12. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy012','Nemo',675,'Nemo.png',getdate()-1,'Kim')  
  13. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy013','Old Car',1950,'OldCar.png',getdate()-3,'Jack')  
  14. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy014','Red Car',679,'RedCar.png',getdate(),'Lee')  
  15. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy015','Soccer Ball',950,'SoccerBall.png',getdate(),'Shanu')  
  16. Insert into ToysDetails(Toy_ID,Toy_Name,Toy_Price,Image_Name,Item_Date,AddedBy) values('Toy016','Tennis Ball',350,'TennisBall.png',getdate()-29,'Afraz')  
  17.   
  18.   
  19. select * from ToysDetails  
  • Create WCF REST Service
Open Visual Studio 2013 then select File - New - Project then select WCF Service Application then select your project path and provide a name for your WCF service and click OK.



Once we created our WCF Service we can see “IService.CS” and “Service1.svc” in the Solution Explorer as in the following.



IService.CS: In “IService.CS” we can see 3 Contracts by default.

[ServiceContract]: Describes the Methods or any operations available for the service. Service Contract is an interface and the methods can be declared inside the service interface using the Operation Contract attribute.

[OperationContract]: is similar to the web service [WEBMETHOD]

[DataContract]:
describes the data exchange between the client and the service.

[ServiceContract]

The following code will be automatically created for all the IService.CS files. We can change and write our own code here.
  1. public interface IService1  
  2.    {  
  3.   
  4.        [OperationContract]  
  5.        string GetData(int value);  
  6.   
  7.        [OperationContract]  
  8.        CompositeType GetDataUsingDataContract(CompositeType composite);  
  9.   
  10.        // TODO: Add your service operations here  
  11.    }  
  12.    // Use a data contract as illustrated in the sample below to add composite types to service operations.  
  13.    [DataContract]  
  14.    public class CompositeType  
  15.    {  
  16.        bool boolValue = true;  
  17.        string stringValue = "Hello ";  
  18.   
  19.        [DataMember]  
  20.        public bool BoolValue  
  21.        {  
  22.            get { return boolValue; }  
  23.            set { boolValue = value; }  
  24.        }  
  25.   
  26.        [DataMember]  
  27.        public string StringValue  
  28.        {  
  29.            get { return stringValue; }  
  30.            set { stringValue = value; }  
  31.        }  
  32.    } 
Data Contract

In our example we need to get all the Toys details, so I have created a Data Contract “ToyItemDataContract”. Here we can see we have decelerated our entire Table column name as Data Member.
  1. public class ToysDetailDataContract  
  2.     {  
  3.         [DataContract]  
  4.         public class ToyItemDataContract  
  5.         {  
  6.             [DataMember]  
  7.             public string Toy_ID { getset; }  
  8.   
  9.             [DataMember]  
  10.             public string Toy_Name { getset; }  
  11.   
  12.             [DataMember]  
  13.             public string Toy_Price { getset; }  
  14.   
  15.             [DataMember]  
  16.             public string Image_Name { getset; }  
  17.   
  18.             [DataMember]  
  19.             public string Item_Date { getset; }  
  20.   
  21.             [DataMember]  
  22.             public string AddedBy { getset; }  
  23.         }  
  24.   
  25.     } 
Service Contract

In Operation Contract we can see “WebInvoke” and “WebGet” that retrieves the data from the database in the REST Serivce.
  1. RequestFormat = WebMessageFormat.Json,  
  2. ResponseFormat = WebMessageFormat.Json, 
Here we can see both the request and response format. Here I have used the JSON format.

JSON: JavaScript Object Notation; it is a lightweight data interchange format.

UriTemplate is our method name and here our method return type is List.

Here I have declared a “GetToyDetails” method for getting the details of all the Toys from the database.
  1. [ServiceContract]  
  2.     public interface IService1  
  3.     {  
  4. [OperationContract]  
  5.         [WebInvoke(Method = "GET",  
  6.            RequestFormat = WebMessageFormat.Json,  
  7.            ResponseFormat = WebMessageFormat.Json,  
  8.            UriTemplate = "/GetToyDetails/")]  
  9.         List<ToysDetailDataContract.ToyItemDataContract> GetToyDetails();
  10.     } 
The following is the complete source code of Iservice.Cs:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8.   
  9. namespace Shanu_AngularJsFilterWcfService  
  10. {.  
  11.      [ServiceContract]  
  12.     public interface IService1  
  13.     {  
  14.         [OperationContract]  
  15.         [WebInvoke(Method = "GET",  
  16.            RequestFormat = WebMessageFormat.Json,  
  17.            ResponseFormat = WebMessageFormat.Json,  
  18.            UriTemplate = "/GetToyDetails/")]  
  19.         List<ToysDetailDataContract.ToyItemDataContract> GetToyDetails();   
  20.     }  
  21.     public class ToysDetailDataContract  
  22.     {  
  23.         [DataContract]  
  24.         public class ToyItemDataContract  
  25.         {  
  26.             [DataMember]  
  27.             public string Toy_ID { get; set; }  
  28.   
  29.             [DataMember]  
  30.             public string Toy_Name { get; set; }  
  31.   
  32.             [DataMember]  
  33.             public string Toy_Price { get; set; }  
  34.   
  35.             [DataMember]  
  36.             public string Image_Name { get; set; }  
  37.   
  38.             [DataMember]  
  39.             public string Item_Date { get; set; }  
  40.   
  41.             [DataMember]  
  42.             public string AddedBy { get; set; }  
  43.         }  
  44.   
  45.     }  

Add Database using ADO.NET Entity Data Model

Right-click your WCF project and select Add New Item then select ADO.NET Entity Data Model and click Add.



Select EF Designer from Database and click Next.



Click New Connection.



Here we can select our Database Server Name and enter our database server's SQL Server Authentication User ID and Password. We have already created our database as “ToysDB” so we can select the database and click OK.



Click Next and select the tables we need and click Finish.

Here we can see now we have created our shanuToyDetailsModel.




Service1.SVC

In “Service.SVC.CS” implements the IService Interface and overrides and defines all the methods of Operation Contract.

For example here we can see I have implemented the IService1 in the Service1 class. I created the object for our Entity model and in the GetToyDetailsusing LINQ Query.
  1. public class Service1 : IService1  
  2.     {  
  3. shanuToysDBEntities OME;  
  4.   
  5.         public Service1()  
  6.         {  
  7.             OME = new shanuToysDBEntities();  
  8.         }  
  9.   
  10. public List<ToysDetailDataContract.ToyItemDataContract> GetToyDetails()  
  11.         {  
  12.             var query = (from a in OME.ToysDetails  
  13.                          select a).Distinct();  
  14.   
  15.             List<ToysDetailDataContract.ToyItemDataContract> ToyDetailList = new List<ToysDetailDataContract.ToyItemDataContract>();  
  16.   
  17.             query.ToList().ForEach(rec =>  
  18.             {  
  19.                 ToyDetailList.Add(new ToysDetailDataContract.ToyItemDataContract  
  20.                 {  
  21.                     Toy_ID = rec.Toy_ID,  
  22.                     Toy_Name = rec.Toy_Name,  
  23.                     Toy_Price = Convert.ToString(rec.Toy_Price),  
  24.                     Image_Name = rec.Image_Name,  
  25.                     Item_Date = Convert.ToString(rec.Item_Date),  
  26.                     AddedBy = rec.AddedBy  
  27.   
  28.                 });  
  29.             });  
  30.             return ToyDetailList;  
  31.         } 
“Service.SVC.CS”: Complete Source Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using shanu_AngularJsFilter.Model;  
  9.   
  10. namespace shanu_AngularJsFilter  
  11. {  
  12. public class Service1 : IService1  
  13.     {  
  14.         shanuToysDBEntities OME;  
  15.   
  16.         public Service1()  
  17.         {  
  18.             OME = new shanuToysDBEntities();  
  19.         }  
  20.   
  21. public List<ToysDetailDataContract.ToyItemDataContract> GetToyDetails()  
  22.         {  
  23.             var query = (from a in OME.ToysDetails  
  24.                          select a).Distinct();  
  25.   
  26.             List<ToysDetailDataContract.ToyItemDataContract> ToyDetailList = new List<ToysDetailDataContract.ToyItemDataContract>();  
  27.   
  28.             query.ToList().ForEach(rec =>  
  29.             {  
  30.                 ToyDetailList.Add(new ToysDetailDataContract.ToyItemDataContract  
  31.                 {  
  32.                     Toy_ID = rec.Toy_ID,  
  33.                     Toy_Name = rec.Toy_Name,  
  34.                     Toy_Price = Convert.ToString(rec.Toy_Price),  
  35.                     Image_Name = rec.Image_Name,  
  36.                     Item_Date = Convert.ToString(rec.Item_Date),  
  37.                     AddedBy = rec.AddedBy  
  38.   
  39.                 });  
  40.             });  
  41.             return ToyDetailList;  
  42.         }  
  43.          
  44.     }  

Web.Config

In the WCF project “Web.Config”:
  1. Change <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />
  2. Replace the </behaviors> to:
  1. <behavior>
  2.      <endpointBehaviors>
  3.           <webHttp helpEnabled="True"/>  
  4.         </behavior>  
  5.     </endpointBehaviors>  
  6. </behaviors> 
Run WCF Service: Now we have created our WCF Rest service, let's run and test our service. In our service URL we can add our method name and we can see the JSON result data from the database.



Create MVC Web Application

So now we have completed our WCF and now it's time to create our MVC AngularJS application.

We can add a new project to our existing project and create a new MVC web application as in the following.

Right-click your solution and click Add New Project then enter your project name and click OK.



Select MVC and Click OK.



Now we have created our MVC application and it's time to add our WCF Service and install the AngularJS package to our solution.

Add WCF Service: Right-click MVC Solution and click Add then click Service Reference.



Enter your WCF URL and click GO. Here my WCF URL is http://localhost:5029/Service1.svc/

Add your name and click OK.

Now we have successfully added our WCF Service to our MVC Application.



Procedure to Install AngularJS package

Right-click your MVC project and click Manage NuGet Packages.



Select Online and Search for AngularJS. Select the AngularJs and click Install.



Now we have Installed AngularJS package to our MVC Project. Now let's create our AngularJs.
  • Modules.js
  • Controllers.js
  • Services.js
Procedure to Create AngularJs Script Files

Right-click the Script folder and create your own folder to create our AngularJs Model/Controller and Service JavaScript. In your script folder add three JavaScript files and name them Modules.js, Controllers.js and Services,js as in the following.



Modules.js: Here we add the reference to the Angular.js JavaScript. In our application we will use AngularJs animation. To use the animation we need to add the “angular-animate.js” and “angular-animate.min.js” files. We provide our module name as “RESTClientModule” and to use the animation we need to pass the parameter to our module as "ngAnimate".
  1. /// <reference path="../angular.js" />  
  2. /// <reference path="../angular.min.js" />  
  3. /// <reference path="../angular-animate.js" />  
  4. /// <reference path="../angular-animate.min.js" />  
  5. var app;  
  6. (function ()  
  7. {  
  8.     app = angular.module("RESTClientModule", ['ngAnimate']);  
  9. })(); 
Services.js: Here we add the reference to the Angular.js JavaScript and our Module.js.

Here we provide a name of our service and we use this name in controllers.js. Here for the Angular service I have given the name as "AngularJs_WCFService". You can provide your own name but be careful about changing the name in Controllers.js. Here we can see in the method since I have passed the URL of our WCF Service URL.
  1. /// <reference path="../angular.js" />  
  2. /// <reference path="../angular.min.js" />  
  3. /// <reference path="../angular-animate.js" />  
  4. /// <reference path="../angular-animate.min.js" />  
  5. /// <reference path="Modules.js" />  
  6.   
  7. app.service("AngularJs_WCFService", function ($http)  
  8. {  
  9.      //Get Order Master Records  
  10.      this.GetToyDetails = function ()  
  11. {  
  12.    return $http.get("http://localhost:5029/Service1.svc/GetToyDetails/");  
  13. };  
  14.   
  15. }); 
Controllers.js: Here we add the reference to the Angular.js JavaScript and our Module.js and Services.js. The same as services, for the controller I have given the name "AngularJs_WCFController".

In the Controller I have performed all the business logic and returned the data from the WCF JSON data to our MVC HTML page.
  1. Variable declarations:

    First I declared all the local variables that need to be used and the current date and store the date using $scope.date.

  2.  Methods:

    GetToyDetails()

    This method is used to get all the details of Toys from the JSON and bind the result to the main page.

    $scope.showImage

  3. $scope.showImage = function (imageNm, ToyCode, ToyName, ToyPrize,animatval) {

    In the image mouse over we get the details and display the data and image in detail view. In this method I have used the $scope.showAnim Boolean value to fade in and fade out the Image in details display.
Controller.js full source code
  1. /// <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. /// <reference path="Modules.js" />     
  6. /// <reference path="Services.js" />     
  7.   
  8. app.controller("AngularJs_WCFController"function ($scope,$timeout, $rootScope, $window, AngularJs_WCFService) {  
  9.     $scope.date = new Date();  
  10.  //  To show and Hide the Table to display  Character Type Selection and Question  
  11.     var firstbool = true;    
  12.     $scope.Imagename = "";  
  13.     $scope.ToyCode = "";  
  14.     $scope.ToyName = "";  
  15.     $scope.ToyPrize = "";  
  16.     $scope.showAnim = true;  
  17.   
  18. GetToyDetails();  
  19.     //To Get All Records     
  20.     function GetToyDetails()
  21.       {  
  22.         var promiseGet = AngularJs_WCFService.GetToyDetails();  
  23.         promiseGet.then(function (pl) {  
  24.             $scope.getToyDetailsDisp = pl.data  
  25.             if($scope.getToyDetailsDisp.length>0)  
  26.                {                 
  27.                    $scope.Imagename = $scope.getToyDetailsDisp[0].Image_Name;  
  28.                    $scope.ToyCode = $scope.getToyDetailsDisp[0].Toy_ID;  
  29.                    $scope.ToyName = $scope.getToyDetailsDisp[0].Toy_Name;  
  30.                    $scope.ToyPrize = $scope.getToyDetailsDisp[0].Toy_Price;                 
  31.               }  
  32.             else  
  33. {  
  34.                 $scope.Imagename = "";  
  35.                 $scope.ToyCode ="";  
  36.                 $scope.ToyName = "";  
  37.                 $scope.ToyPrize = "";  
  38.             }  
  39.         },  
  40.              function (errorPl)  
  41.     {  
  42.              });  
  43.     }  
  44.     $scope.showImage = function (imageNm, ToyCode, ToyName, ToyPrize,animatval) {  
  45.         $scope.Imagename = imageNm;  
  46.         $scope.ToyCode = ToyCode;  
  47.         $scope.ToyName = ToyName;  
  48.         $scope.ToyPrize = ToyPrize;       
  49.         if(animatval==1)  
  50.         {            
  51.             $scope.showAnim = false;             
  52.         }  
  53.         else  
  54.         {  
  55.             $scope.showAnim = true;              
  56.         }         
  57.     }}); 
So now we have created our AngularJs Module, Controller and Service. So what is next?

Create MVC Control and View to display our result.

Add Controller:

Right-click Controllers then select Add Controller then select MVC 5 Controller –Empty then click Add.



Change the Controller name and here I have given it the name “shanuToysController” and click OK.

Add View: Right-click on the Controller Index and click Add View.



Index View: Name the View “Index”.

In View Design your page and reference of angular.Js, Modules.js, Services.js and Controllers.js.

In AngularJS we use {{ }} to bind or display the data.

Here we can see first I create one table and for that table.

First in the table I used the data-ng-controller="AngularJs_WCFController" and here we can see data-ng-controller will be used to bind the data of the controller to our HTML table.
  • Data Bind using Data-ng-repeat and added Filter and Order By to the details in order to perform the Filter and Sorting to our display.
  1. <tbody data-ng-repeat="detail in getToyDetailsDisp | filter:search | orderBy:predicate:reverse" ng-animate="{enter: 'animate-enter', leave: 'animate-leave'}"
Here I have used ng-animate to display the data when loading with fade In animation.
  • Filter TextBox as in column headers.
  1. <input ng-model="search.Toy_ID" style="width:100px">  
  2. <input ng-model="search.Toy_Name" > 
Here we can see I have used the TextBox to filter each column by their field name.
  • Sort: When the user clicks on Table Heading TD I will sort the appropriate column using the ng-click event
  1. <td ng-click="predicate = 'Toy_Name'; reverse=!reverse">  
  2.        <b>Toy Name</b>  
  3.  </td> 
  • Image Mouse Over and Mouse Event to display the detail image with animation.
  1. <img src="~/Images/Thumb/{{detail.Image_Name}}" alt="{{detail.Toy_Name}}" ng-mouseover="showImage(detail.Image_Name,detail.Toy_ID,detail.Toy_Name,detail.  
  2. Toy_Price,1)" ng-mouseleave="showImage(detail.Image_Name,detail.Toy_ID,detail.Toy_Name,  
  3. detail.Toy_Price,2)"> 
In Detail image
  1. <div >  
  2.      <div class="animate-show" ng-show="showAnim">  
  3.          <img alt="" src="~/Images/Actual/{{Imagename}}" />  
  4.       </div>                                 
  5.   </div> 
Complete HTML Code
  1. <style type="text/css">  
  2.     .ng-enter   
  3.       {  
  4.           -webkit-transition: 1s;  
  5.           transition: 1s;  
  6.           opacity:0;  
  7.       }  
  8.       .ng-enter-active   
  9.       {  
  10.           -webkit-transition: 1s;  
  11.           transition: 1s;  
  12.           opacity:1;  
  13.       }   
  14.       .ng-leave   
  15.       {  
  16.           -webkit-transition: 1s;  
  17.           transition: 1s;  
  18.       }  
  19.       .ng-leave-active   
  20.       {  
  21.           opacity:0;  
  22.       }  
  23.       .animate-show
    {  
  24.   opacity: 1;  
  25. }  
  26. .animate-show.ng-hide-add.ng-hide-add-active,  
  27. .animate-show.ng-hide-remove.ng-hide-remove-active {  
  28.   -webkit-transition: all linear 0.5s;  
  29.   transition: all linear 0.5s;  
  30. }  
  31. .animate-show.ng-hide {  
  32.   opacity: 0;  
  33. }  
  34. </style>  
  35. <html data-ng-app="RESTClientModule">  
  36. @{  
  37.     ViewBag.Title = "Angular JS Filters and Sorting";  
  38. }  
  39. <body>  
  40.     <img src="~/Images/blank.gif" alt="" width="1" height="10" />  
  41.     <table width="99%" style=" border-bottom:3px solid #3273d5;">  
  42.         <tr>
  43.            <td width=" 250">  
  44.                 <table width="99%">  
  45.                     <tr>  
  46.                         <td>  
  47.                             Welcome Mr. {{'SHANU'}} .
  48.                         </td>  
  49.                     </tr>  
  50.                 </table>  
  51.             </td>  
  52.             <td class="style1" align="center">  
  53.                 <h3>Shanu - ANgularJs Filter and Sorting with simple Animation using MVC and WCF Rest Service  :)</h3>  
  54.             </td>  
  55.             <td align="right">  
  56.                 <div ng-controller="AngularJs_WCFController">  
  57.                     Today Date is :  
  58.                     {{date | date:'yyyy-MM-dd'}}  
  59.                 </div>
  60.             </td>  
  61.         </tr>  
  62.     </table>  
  63.     <img src="~/Images/blank.gif" alt="" width="1" height="10" />
  64.     <table id="tblContainer" data-ng-controller="AngularJs_WCFController" style='width: 99%;table-layout:fixed;'>  
  65.         <tr>  
  66.             <td >  
  67.                 <table style=" background-color:#FFFFFF; border: solid 2px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2" cellspacing="2">  
  68.                     <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  69.                         <td >  
  70.                             Toy Image  
  71.                         </td>  
  72.                         <td>  
  73.                             Toy Details  
  74.                         </td>  
  75.                     </tr>  
  76.                     <tr style="height: 30px; background-color:#FFFFFF ; color:#336699 ;border: solid 1px #659EC7;">  
  77.                         <td >    
  78.                             <div >  
  79.                                 <div class="animate-show" ng-show="showAnim">  
  80.                                    <img alt="" src="~/Images/Actual/{{Imagename}}" />  
  81.                                 </div>                                 
  82.                             </div>  
  83.                         </td>  
  84.                         <td>  
  85.                             <h3 style="color:#9F000F"> Toy Code : <b>{{ToyCode}} </b></h3><br />  
  86.                             <h3 style="color:#9F000F"> Toy Name : <b>{{ToyName}} </b></h3><br />  
  87.                             <h3 style="color:#9F000F"> Toy Price : <b>{{ToyPrize}} </b></h3><br />    
  88.                         </td>  
  89.                     </tr>  
  90.                 </table>
  91.             </td>  
  92.         </tr>  
  93.         <tr>  
  94.             <td>  
  95.                 <table style=" background-color:#FFFFFF; border: solid 2px #6D7B8D; padding: 5px;width: 99%;table-        layout:fixed;" cellpadding="2" cellspacing="2">  
  96.                     <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  97.                         <td width="40" align="center">  
  98.                         <b>Image</b>  
  99.                         </td>  
  100.                         <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed; cursor: pointer;" ng-click="predicate = 'Toy_ID'; reverse=!reverse">  
  101.                             <b>Toy Code</b>  
  102.                         </td>  
  103.                         <td width="120" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;" ng-click="predicate = 'Toy_Name'; reverse=!reverse">  
  104.                             <b>Toy Name</b>  
  105.                         </td>  
  106.                         <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;" ng-click="predicate = 'Toy_Price'; reverse=!reverse">  
  107.                             <b>Price</b>  
  108.                         </td>  
  109.                         <td width="90" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;" ng-click="predicate = 'Item_Date'; reverse=!reverse">  
  110.                             <b>Date</b>  
  111.                         </td>  
  112.                         <td width="90" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;cursor: pointer;" ng-click="predicate = 'AddedBy'; reverse=!reverse">  
  113.                             <b>User Name</b>  
  114.                         </td>  
  115.                     </tr>  
  116.                     <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  117.                         <td width="40" align="center">  
  118.                            Filter By ->  
  119.                         </td>  
  120.                         <td width="40" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">  
  121.                             <input ng-model="search.Toy_ID" style="width:100px">  
  122.                         </td>  
  123.                         <td width="120" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">  
  124.                             <input ng-model="search.Toy_Name" placeholder="filter Name...">  
  125.                         </td>  
  126.                         <td width="40" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">
  127.                         </td>  
  128.                         td width="90" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">  
  129.                             <input ng-model="search.Item_Date">  
  130.                         </td>  
  131.                         <td width="90" align="center" style="border: solid 1px #FFFFFF; padding: 5px;table-layout:fixed;">  
  132.                             <input ng-model="search.AddedBy">  
  133.                         </td>  
  134.                     </tr>  
  135.                     <tbody data-ng-repeat="detail in getToyDetailsDisp | filter:search  | orderBy:predicate:reverse" ng-animate="{enter: 'animate-enter', leave: 'animate-leave'}">  
  136.                         <tr>  
  137.                             <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  138.                                 <span style="color:#9F000F">  
  139.                                     <img src="~/Images/Thumb/{{detail.Image_Name}}" alt="{{detail.Toy_Name}}" ng-mouseover="showImage(detail.Image_Name,detail.Toy_ID,detail.Toy_Name,detail.Toy_Price,1)"  
  140.                                          ng-mouseleave="showImage(detail.Image_Name,detail.Toy_ID,detail.Toy_Name,detail.Toy_Price,2)">  
  141.                                 </span>  
  142.                             </td>  
  143.                             <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  144.                                 <span style="color:#9F000F">  
  145.                                     {{detail.Toy_ID}}  
  146.                                 </span>
  147.                             </td>  
  148.                             <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  149.                                 <span style="color:#9F000F">  
  150.                                     {{detail.Toy_Name}}  
  151.                                 </span>  
  152.                             </td>  
  153.                             <td align="right" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  154.                                 <span style="color:#9F000F">  
  155.                                     {{detail.Toy_Price}}  
  156.                                 </span>  
  157.                             </td>
  158.                             <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  159.                                 <span style="color:#9F000F">  
  160.                                     {{detail.Item_Date}}  
  161.                                 </span>
  162.                             </td>  
  163.                             <td style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  164.                                 <span style="color:#9F000F">  
  165.                                     {{detail.AddedBy}}  
  166.                                 </span>  
  167.                             </td>  
  168.                         </tr>  
  169. </table>  
  170.             </td>  
  171.         </tr>  
  172. </table>  
  173.     <img src="~/Images/blank.gif" alt="" width="1" height="10" />  
  174. </body>  
  175.   
  176. </html>  
  177. <script src="~/Scripts/angular.js"></script>  
  178. <script src="~/Scripts/angular-animate.js"></script>  
  179. <script src="~/Scripts/angular-animate.min.js"></script>  
  180. <script src="~/Scripts/angular.min.js"></script>  
  181. <script src="~/Scripts/shanuAngularScript/Modules.js"></script>  
  182. <script src="~/Scripts/shanuAngularScript/Services.js"></script>  
  183. <script src="~/Scripts/shanuAngularScript/Controllers.js"></script> 
Run your program

Here we can see that when I run the program I first display all the Toy details.



Filter by Toy Name. Here we can see in the Toy Name Filter, I have entered the car and in the table we can see only the toy names that has car.



Next we can see the same preceding result has been sorted by Toy Code in reverse order.



Note

In my application Image folder I have add both a Thumb and Actual image. In Database I have provided the same names as in both folders. If you need to add more photos you can add in both folders and in the database kindly add the image name as in the folder with a new record or update with an existing record.

Supported Browsers: Chrome and Firefox.