Share via


MVC Dynamic Menu Creation Using AngularJS and WCF Rest

 You can download the Source Code from this link Download Source Code 

Introduction

https://code.msdn.microsoft.com/site/view/file/141033/1/shanuMenuAngular.gif

*  This article shows how to create a menu dynamically from a database using AngularJS, MVC and WCF Rest service.*

Why we need to create a Dynamic Menu

If we are working on a simple web site creation with very few pages and only one programmer is working to create a website then in that case we can create a static menu and use it in our web site.

Let's now consider we need to work for a big web application project. Let's consider development of an ERP Web application.

However if more than two developers are working and perhaps the number of pages is greater than 50 to 100 then it will be hard to maintain a static menu.

And also there will be a greater chance of removing and adding a new menu item to the web project, for example our client can ask to add 5 more new menus or remove 1 menu item.

In this case it will be a hard and difficult task to remove the menu Items that are live now.

And also for large web projects like ERP we need to display the menu depending on the user roles. If we use a static menu then it will be very difficult to manage the users for the menu.

To avoid all this we create a Menu Management with a user role setting.

Who can manage the Menu

This is a very important part since an Admin or Super user can Add/Edit/Delete a menu and a user.

When an Admin is logged in he can add a new menu, edit an existing menu and delete a menu item to be displayed.

This article is not focused on menu management but in this article we will see in detail how to create a Menu Master and Menu Detail Table. Insert a sample Menu Item to our Database Tables. Display the Menu from the database dynamically to our MVC Web page using AngularJS and WCF Rest Service. This article will explain:

  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 for Dynamic Menu Creation.
  4. How to use a WCS service in AngularJS to display dynamic Menu.

Note: the prerequisites are Visual Studio 2013 (if you don't have Visual Studio 2013, you can download it from Microsoft.(You can download latest Visual Studio 2015 and use for the same).
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 this protocol the service can be shared and used over a network.
For example, let's consider that we are now working on a project and we need to create some common database function and those functions need to be used in multiple projects and the projects are in multiple places and connected via a network such as 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 DB 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 details about WCF then kindly go to this link.

AngularJS 

We might be be familiar with what Model, View and View Model (MVVM) is and what Model, View and Controller (MVC) is. AngularJS is a JavaScript framework that is purely based on HTML, CSS and JavaScript.
Similar to the MVC and MVVM patterns AngularJS uses the Model, View and Whatever (MVW) pattern.
In our example I have used a Model, View and Service. In the code part let's see how to install and create AngularJS in our MVC application. 
If you are interested in reading more details about AngularJS then kindly go to this link.

Building the Sample

We will create a MenuMaster MenuDetails table under the Database MenuDB.

Note: The MenuMaster and MenuDetail are the important tables that will use to load our menu dynamically. We need to understand how to insert menu details to these tables to display our menu properly.

In this article I have displayed a 3-level hierarchical display of menus. Here we can see the 3-level hierarchical sample.

https://code.msdn.microsoft.com/site/view/file/141035/1/M4.jpg

  

Here we can see that the first level of the hierarchy is the Inventory.

The 3rd level of the hierarchy is the Finished Goods Receipt and Finished Goods Issue.

Now let's see how to create a table relationship to create the master and detail menus.

  • **     1st Level hierarchy Insert**
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Root','Inventory','Shanu',getdate()-23)
  • 2nd Level hierarchies Insert
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Inventory','INV001','Shanu',getdate()-23)
  • 3rd Level hierarchies Insert
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('INV001','FG001','Shanu',getdate()-23)   
    
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('INV001','FG002','Shanu',getdate()-23)

Here we can see the fields for the Menu Master. I have used the following fields:

https://code.msdn.microsoft.com/site/view/file/141036/1/14.jpg

  • 1st Level hierarchy Insert
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,   
MenuURL,UserID,CreatedDate)   
values('Inventory','Inventory','Inventory','Index','Inventory',   
'Shanu',getdate()-23)
  • 2nd Level hierarchies Insert
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,   MenuURL,UserID,CreatedDate)   
values('INV001','Inventory','Inventory Details','Index','Inventory',   
'Shanu',getdate()-23)
  • 3rd Level hierarchies Insert
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,  MenuURL,UserID,CreatedDate)   
values('FG001','FGIN','FG Receipt','FGIN','Inventory','Shanu',getdate()-43)   
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,   MenuURL,UserID,CreatedDate)   
values('FG002','FGOUT','FG Issue','FGOUT','Inventory','Shanu',getdate()-13)

Here we can see the field for the Menu Detail. I have used the following fields.

 https://code.msdn.microsoft.com/site/view/file/141037/1/15.jpg

-- =============================================                                   
-- Author      : Shanu                         
-- Create date : 2015-03-20                
-- Description : To Create Database,Table and Sample Insert Query                                
-- Latest  
-- Modifier    : Shanu  
-- Modify date : 2015-03-20                               
-- =============================================   
--Script to create DB,Table and sample Insert data   
USE MASTER   
GO   
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
IF EXISTS (SELECT [name] FROM  sys.databases WHERE  [name] = 'MenuDB' )    
DROP DATABASE  MenuDB   
GO   
    
CREATE DATABASE  MenuDB   
GO   
    
USE MenuDB   
GO   
    
-- 1) //////////// ToysDetails table   
-- Create Table  ToysDetails ,This table will be used to store the details like Toys Information    
    
IF EXISTS ( SELECT  [name] FROM  sys.tables WHERE  [name] = 'MenuMaster' )   
DROP TABLE  MenuMaster   
GO   
    
CREATE TABLE  MenuMaster   
(   
   Menu_ID int  identity(1,1),   
   Menu_RootID VARCHAR(30)  NOT NULL,   
   Menu_ChildID VARCHAR(30)  NOT NULL,   
   UserID varchar(50),   
   CreatedDate datetime   
CONSTRAINT [PK_MenuMaster] PRIMARY KEY  CLUSTERED         
(        
  [Menu_ID] ASC    ,   
  [Menu_RootID] ASC,   
  [Menu_ChildID] ASC    
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON  [PRIMARY]        
) ON  [PRIMARY]      
    
GO   
--delete from MenuMaster   
-- Insert the sample records to the ToysDetails Table   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Root','Home','Shanu',getdate()-23)   
--Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Home','Home','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Home','About','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Home','Contact','Shanu',getdate()-23)   
    
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Root','Masters','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Masters','ITM001','Shanu',getdate()-23)   
--Insert into MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('ITM001','ITM001','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('ITM001','ITM002','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('ITM001','ITM003','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Masters','CAT001','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('CAT001','CAT001','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('CAT001','CAT002','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('CAT001','CAT003','Shanu',getdate()-23)   
    
    
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Root','Inventory','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('Inventory','INV001','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('INV001','FG001','Shanu',getdate()-23)   
Insert into  MenuMaster(Menu_RootID,Menu_ChildID,UserID,CreatedDate) values('INV001','FG002','Shanu',getdate()-23)   
    
    
    
select * from MenuMaster   
-- 1) END //   
    
-- 2) Cart Details Table   
IF EXISTS ( SELECT  [name] FROM  sys.tables WHERE  [name] = 'MenuDetails'  )   
DROP TABLE  MenuDetails   
GO   
    
CREATE TABLE  MenuDetails   
(   
   MDetail_ID int  identity(1,1),   
   Menu_ChildID VARCHAR(20) NOT NULL,   
   MenuName VARCHAR(100) NOT NULL,   
   MenuDisplayTxt VARCHAR(200) NOT NULL,   
   MenuFileName VARCHAR(100) NOT NULL,    
   MenuURL VARCHAR(500) NOT NULL,   
   USE_YN Char(1) DEFAULT  'Y',   
   UserID varchar(50),   
   CreatedDate datetime   
CONSTRAINT [PK_MenuDetails] PRIMARY KEY  CLUSTERED         
(        
  [MDetail_ID] ASC,   
  [Menu_ChildID] ASC         
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON  [PRIMARY]        
) ON  [PRIMARY]      
    
GO   
----delete from MenuDetails   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('Root','Home','Shanu Home','Index','Home','Shanu',getdate()-23)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('Home','Home','Shanu Home','Index','Home','Shanu',getdate()-23)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('About','About','About Shanu','About','Home','Shanu',getdate()-43)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('Contact','Contact','Contact Shanu','Contact','Home','Shanu',getdate()-13)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('Masters','Masters','Masters','ItemDetails','Masters','Shanu',getdate()-13)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('ITM001','ItemMaster','Item Master','ItemDetails','Masters','Shanu',getdate()-13)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('ITM002','ItemDetail','Item Details','ItemDetails','Masters','Shanu',getdate()-13)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('ITM003','ItemManage','Item Manage','ItemManage','Masters','Shanu',getdate()-13)   
    
    
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('CAT001','CatMaster','Category Masters','CATDetails','Masters','Shanu',getdate()-13)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('CAT002','CATDetail','Category Details','CATDetails','Masters','Shanu',getdate()-13)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('CAT003','CATManage','Category Manage','CATManage','Masters','Shanu',getdate()-13)   
    
    
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('Inventory','Inventory','Inventory','Index','Inventory','Shanu',getdate()-23)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('INV001','Inventory','Inventory Details','Index','Inventory','Shanu',getdate()-23)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('FG001','FGIN','FG Receipt','FGIN','Inventory','Shanu',getdate()-43)   
    
Insert into  MenuDetails(Menu_ChildID,MenuName,MenuDisplayTxt,MenuFileName,MenuURL,UserID,CreatedDate)    
values('FG002','FGOUT','FG Issue','FGOUT','Inventory','Shanu',getdate()-13)   
    
    
select * from MenuMaster   
    
select * from MenuDetails   
    
        select   A.Menu_RootID,   
                 B.MDetail_ID,   
                 B.Menu_ChildID,   
                 B.MenuName,   
                 B.MenuDisplayTxt,   
                 B.MenuFileName,              
                 B.MenuURL ,              
                 B.UserID                                                         
                 FROM   
                 MenuMaster A   
                 INNER JOIN MenuDetails B   
                 ON A.Menu_ChildID=B.Menu_ChildID

Description

*Now we have created our Tables lest start with creating WCF Rest service to access the data abd display in our Angular JS MVC page.
*
Create WCF REST Service

Open Visual Studio 2013 then select "File" -> "New" -> "Project..." then select WCF Service Application then select the project path and name the WCF service and click OK.

https://code.msdn.microsoft.com/site/view/file/141038/1/1.jpg

Once we have created the WCF Service we can see “IService.CS” and “Service1.svc” in the Solution 

https://code.msdn.microsoft.com/site/view/file/141039/1/2.jpg

  • IService.CS: In “IService.CS” we can see 3 contracts by default.
  • [ServiceContract]: Describes the methods or any operations available for the service. The Service Contract is an interface and 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.

public interface  IService1   
{   
    
    [OperationContract]   
    string GetData(int value);   
    
    [OperationContract]   
    CompositeType GetDataUsingDataContract(CompositeType composite);   
    
    // TODO: Add your service operations here   
}   
// Use a data contract as illustrated in the sample below to add composite types to service operations.   
[DataContract]   
public class  CompositeType   
{   
    bool boolValue = true;   
    string stringValue = "Hello ";   
    
    [DataMember]   
    public bool  BoolValue   
    {   
        get { return boolValue; }   
        set { boolValue = value; }   
    }   
    
    [DataMember]   
    public string  StringValue   
    {   
        get { return stringValue; }   
        set { stringValue = value; }   
    }   
}

**Data Contract **In our example we need to get all the Menu Details from the database, so I have created the Data Contracts “MenuDataContract”. Here we can see we have decelerated our entire table column name as Data Member.

public class  MenuDataContract   
    {   
        [DataContract]   
        public class  MenuMasterDataContract   
        {   
            [DataMember]   
            public string  Menu_ID { get; set; }   
    
            [DataMember]   
            public string  Menu_RootID { get; set; }   
    
            [DataMember]   
            public string  Menu_ChildID { get; set; }   
    
            [DataMember]   
            public string  UserID { get; set; }   
    
        }   
    
        [DataContract]   
        public class  MenuDetailDataContract   
        {   
            [DataMember]   
            public string  MDetail_ID { get; set; }   
    
            [DataMember]   
            public string  Menu_RootID { get; set; }   
    
            [DataMember]   
            public string  Menu_ChildID { get; set; }   
    
            [DataMember]   
            public string  MenuName { get; set; }   
    
            [DataMember]   
            public string  MenuDisplayTxt { get; set; }   
    
            [DataMember]   
            public string  MenuFileName { get; set; }   
    
            [DataMember]   
            public string  MenuURL { get; set; }   
    
            [DataMember]   
            public string  UserID { get; set; }   
        }   
    
    }

**Service Contract: **In the Operation Contract we can see “WebInvoke” and “WebGet” for retrieving the data from the database in the REST Service. 

RequestFormat = WebMessageFormat.Json,   
ResponseFormat = WebMessageFormat.Json,

Here we can see both of the request and response formats. Here I have used the JavaScript Object Notation (JSON) format.

  • JSON is a lightweight data interchange format.
  • UriTemplate: Here we provide our Method Name.

Here I have declared the 3 methods “GetMenuDetails”. The “GetMenuDetails” method gets all the Menu Master and Details that will be used in our AngularJS to display the menu using a filter for each hierarchy.

[ServiceContract]   
    public interface  IService1   
    {   
[OperationContract]   
        [WebInvoke(Method = "GET",    
           RequestFormat = WebMessageFormat.Json,   
           ResponseFormat = WebMessageFormat.Json,   
           UriTemplate = "/GetMenuDetails/")]   
        List<MenuDataContract.MenuDetailDataContract> GetMenuDetails();   
 }

Add Database usingADO.NET Entity Data Model

Right-click the WCF project and select Add New Item then select ADO.NETEntity Data Model and click Add.

 https://code.msdn.microsoft.com/site/view/file/141040/1/3.jpg

 Select EF Designer from Database and click Next.

 https://code.msdn.microsoft.com/site/view/file/141041/1/4.jpg

 Click New Connection.

 https://code.msdn.microsoft.com/site/view/file/141042/1/5.jpg

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

 https://code.msdn.microsoft.com/site/view/file/141043/1/6.jpg

Click Next and select the tables to be used and click Finish.

Here we can see we have now created our ShanuMenuModel.

https://code.msdn.microsoft.com/site/view/file/141044/1/7.jpg 

 Service1.SVC

“Service.SVC.CS” implements the IService Interface and overrides and defines all the methods of the Operation Contract. For example here we can see I have implemented the IService1 in the Service1 class. I have created the object for our Entity model and in GetMenuDetails using a LINQ join query I get both Menu Master and Detaildatas. 

public class  Service1 : IService1   
    {   
        ShanuMenuCreation_WCF.MenuDBEntities OME;   
    
        public Service1()   
        {   
            OME = new  ShanuMenuCreation_WCF.MenuDBEntities();   
        }   
    
        public List<MenuDataContract.MenuDetailDataContract> GetMenuDetails()   
        {   
            ////var query = (from a in OME.MenuDetails   
            ////             select a).Distinct();   
             var query = (from A in  OME.MenuMaster      
                         join B in  OME.MenuDetails on A.Menu_ChildID equals B.Menu_ChildID    
                         select new     
                         {      
                            A.Menu_RootID,   
                            B.MDetail_ID,   
                            B.Menu_ChildID,   
                            B.MenuName,   
                            B.MenuDisplayTxt,   
                            B.MenuFileName,   
                            B.MenuURL ,   
                            B.UserID   
                         }).ToList().OrderBy(q => q.MDetail_ID);     
    
            List<MenuDataContract.MenuDetailDataContract> MenuList = new  List<MenuDataContract.MenuDetailDataContract>();   
    
            query.ToList().ForEach(rec =>   
            {   
                MenuList.Add(new MenuDataContract.MenuDetailDataContract   
                {   
                    MDetail_ID = Convert.ToString(rec.MDetail_ID),   
                    Menu_RootID = rec.Menu_RootID,   
                    Menu_ChildID = rec.Menu_ChildID,   
                    MenuName = rec.MenuName,   
                    MenuDisplayTxt = rec.MenuDisplayTxt,   
                    MenuFileName = rec.MenuFileName,   
                    MenuURL = rec.MenuURL,   
                    UserID = rec.UserID,   
                });   
            });   
            return MenuList;   
        }         
    }

Web.Config

In the WCF project's “Web.Config” make the following changes.

<add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />

Replace the behavior as in the following: 

</behaviors>   
   <endpointBehaviors>   
        <behavior>   
          <webHttp helpEnabled="True"/>   
        </behavior>   
    </endpointBehaviors>   
</behaviors>

**Run WCF Service: **Now that 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.

 https://code.msdn.microsoft.com/site/view/file/141045/1/8.jpg

Create MVC Web Application

We can add a new project to our existing project and create a new MVC web application as in the following.Right-click the project in the solution and click Add New Project then enter to our project name and click "OK".

 https://code.msdn.microsoft.com/site/view/file/141046/1/9.jpg

 Select MVC and click "OK".

 We have now 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.

 https://code.msdn.microsoft.com/site/view/file/141047/1/11.jpg

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

Add the name and click OK.

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

https://code.msdn.microsoft.com/site/view/file/141048/1/12.jpg 

 Procedure to Install AngularJS package

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

 

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

Now we have Installed the AngularJS package into our MVC Project. Now let's create our AngularJS.

  • Modules.js
  • shoppingController.js
  • Services.js

Procedure to Create AngularJS Script Files

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

 https://i1.code.msdn.s-msft.com/angularjs-dynamic-menu-dc974920/image/file/141049/1/13.jpg

Modules.js: Here we add the reference to the Angular.js JavaScript. We provide the module name as“RESTClientModule” . 

/// <reference path="../angular.js" />    
/// <reference path="../angular.min.js" />      
    
var app;   
    
(function () {   
    app = angular.module("RESTClientModule", []);   
})();

Services.js: Here we provide a name for our service and we use this name in shanucontroller.js. Here for the Angular service I have given the name "AngularJs_WCFService". We can provide our own name but be careful of changing the name in Controllers.js. AngularJS can receive JSON data. Here we can see I have provided our WCS service URL to get the Item details as JSON data. To insert an Item information result to the database we pass the data as JSON data to our WCFinsert method as a parameter. 

/// <reference path="../angular.js" />     
/// <reference path="../angular.min.js" />      
    
/// <reference path="Modules.js" />      
       
app.service("AngularJs_WCFService", function  ($http) {   
    //Get Order Master Records     
    this.geMenuDetails = function  () {   
        return $http.get("http://localhost:3514/Service1.svc/GetMenuDetails");   
    };        
    
});

**AngularJS Controller: **Here we add the reference to the Angular.js JavaScript, our Module.js and Services.js. The same as for services. For the controller I have given the name "AngularJsShanu_WCFController". In the Controller I have done all the business logic and returned the data from the WCF JSON data to our MVC HTML page.
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.
**Note: **$scope.subChildIDS = "ITM001"; this variable has been used to filter the 2nd level hierarchy. 
Methods
**getAllMenuDetails(): **In this method I will get all the Menu Detail as JSON and bind the result to the Main page.

 $scope.showsubMenu = function (showMenus,ids) {}

In this method on mouse hover I will filter the 2nd level hierarchy menu details and add the menu items to the list.

shanuController.js full source code

/// <reference path="../angular.js" />     
/// <reference path="../angular.min.js" />      
/// <reference path="Modules.js" />      
/// <reference path="Services.js" />      
      
app.controller("AngularJsShanu_WCFController", function  ($scope, $window, AngularJs_WCFService) {   
    $scope.date = new  Date();   
      $scope.showDetails = false;   
    $scope.showSubDetails = false;   
    $scope.subChildIDS = "ITM001";    
    $scope.Imagename = "R1.png";    
      getAllMenuDetails();   
    //To Get All Records      
    function getAllMenuDetails() {   
          var promiseGet = AngularJs_WCFService.geMenuDetails();    
        promiseGet.then(function (pl) {   
            $scope.MenuDetailsDisp = pl.data   
        },   
             function (errorPl) {   
               });   
    }       
    $scope.showMenu = function  (showMenus) {   
               if (showMenus == 1) {   
            $scope.Imagename = "R2.png"  
            $scope.showDetails = true;   
          }   
        else {   
            $scope.Imagename = "R1.png"  
            $scope.showDetails = false;        }   
    }     
    $scope.showsubMenu = function  (showMenus,ids) {         
        if (showMenus == 1) {   
            $scope.subChildIDS = ids;  
       $scope.showSubDetails = true;           
        }  
        else if(showMenus == 0) {   
            $scope.showSubDetails = false;            
        }        
        else {              
            $scope.showSubDetails = true;             
        }        
    }     
});

So now we have created our AngularJS Module/Controller and Service. So what is next?

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 “MastersController” and click OK.

Add View

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

**MVC Controller CS File: **Here we can in my MVC Controller, I have created 3 menus with sub items. For example I have created the 2 controllers MastersController.cs and InventoryController.cs. 

public class  MastersController : Controller   
    {   
        // GET: Masters   
        public ActionResult Index()   
        { return  View(); }     
    
        public ActionResult ItemDetails()   
        { return  View(); }   
    
        public ActionResult ItemManage()   
        { return  View(); }   
    
        public ActionResult CATDetails()   
        { return  View(); }   
    
        public ActionResult CATManage()   
        { return  View(); }   
    }

Add one more controller as InventoryController.

public class  InventoryController : Controller   
    {   
        // GET: Inventory   
        public ActionResult Index()   
        {   
            return View();   
        }   
    
        public ActionResult FGIN()   
        {    
            return View();   
        }   
        public ActionResult FGOUT()   
        {   
            return View();   
        }   
    }

**Index View

**Name the View “Index”.

In the View, design the page and reference angular.js, Modules.js, Services.js and Controllers.js.

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

Here we can see that I first created a table and something for that table.

First in the table I used the data-ng-controller="AngularJsShanu_WCFController" and here we can see data-ng-controller will be used to bind the data of the controller to the HTML table.

Using < li data-ng-repeat="menus in MenuDetailsDisp | filter:{Menu_RootID:'Root'}" > we can get all the menu details and display the First Level hierarchy menu details as top menu.

Here we can see I have filtered the menu by the rootId "Root". During our insert query I have already explained that for every top-level menu I will provide the Rootid as ‘Root’. First we add all the top-level menus and for each top-level menu if there is any 2nd level hierarchy then I will load the 2nd level menu details to filter by the 1st level RootID as in the following. 

<li data-ng-repeat="menus in MenuDetailsDisp | filter:{Menu_RootID:'Root'}">   
                                        @{   
                                            var url = Url.Action("{{menus.MenuFileName}}", "{{menus.MenuURL}}", new { id = "{{id=menus.MenuURL}}" });   
                                            url = HttpUtility.UrlDecode(url);   
                                        }   
                                        <a data-ng-href="@url">{{menus.MenuDisplayTxt}}</a>   
    
                                        <ul class="sub-menu">   
                                            <li data-ng-repeat="submenus in MenuDetailsDisp | filter:{Menu_RootID:menus.Menu_ChildID}" ng-mouseover="showsubMenu(1,submenus.Menu_ChildID);" ng-mouseout="showsubMenu(0,submenus.Menu_ChildID);">   
                                                @{   
                                                    var url1 = Url.Action("{{submenus.MenuFileName}}", "{{submenus.MenuURL}}", new { id = "{{id=submenus.MenuURL}}" });   
                                                    url1 = HttpUtility.UrlDecode(url1);   
                                                }   
                                                <a data-ng-href="@url1">{{submenus.MenuDisplayTxt}}</a>

**Here we can see for the 2nd level hierarchyI have filtered by **data-ng-repeat="submenus in MenuDetailsDisp | filter :{Menu_RootID:menus.Menu_ChildID}" where menus.Menu_ChildID is the top-level menu id.

Same for the 3rdlevel hierarchy. I will provide the 2nd level hierarchy root id as in the following. 

div style="overflow:visible;height:100px;">   
                                <ul class="menu">   
                                    <li data-ng-repeat="menus in MenuDetailsDisp | filter:{Menu_RootID:'Root'}">   
                                        @{   
                                            var url = Url.Action("{{menus.MenuFileName}}", "{{menus.MenuURL}}", new { id = "{{id=menus.MenuURL}}" });   
                                            url = HttpUtility.UrlDecode(url);   
                                        }   
                                        <a data-ng-href="@url">{{menus.MenuDisplayTxt}}</a>   
    
                                        <ul class="sub-menu">   
                                            <li data-ng-repeat="submenus in MenuDetailsDisp | filter:{Menu_RootID:menus.Menu_ChildID}" ng-mouseover="showsubMenu(1,submenus.Menu_ChildID);" ng-mouseout="showsubMenu(0,submenus.Menu_ChildID);">   
                                                @{   
                                                    var url1 = Url.Action("{{submenus.MenuFileName}}", "{{submenus.MenuURL}}", new { id = "{{id=submenus.MenuURL}}" });   
                                                    url1 = HttpUtility.UrlDecode(url1);   
                                                }   
                                                <a data-ng-href="@url1">{{submenus.MenuDisplayTxt}}</a>   
    
                                                <ul ng-show="showSubDetails" class="sub-menu2">   
                                                    <li data-ng-repeat="sub1menus in MenuDetailsDisp  | filter:{Menu_RootID:subChildIDS}" ng-mouseover="showsubMenu(3,9);">   
                                                        @{   
                                                            var url2 = Url.Action("{{sub1menus.MenuFileName}}", "{{sub1menus.MenuURL}}", new { id = "{{id=sub1menus.MenuURL}}" });   
                                                            url2 = HttpUtility.UrlDecode(url2);   
                                                        }   
                                                        <a data-ng-href="@url2">{{sub1menus.MenuDisplayTxt}}</a>   
                                                    </li>   
                                                </ul>   
    
                                            </li>   
                                        </ul>   
    
                                    </li>   
                                </ul>   
    
                            </div>

Run the Program

(Output Menu Type 1)

https://i1.code.msdn.s-msft.com/angularjs-dynamic-menu-dc974920/image/file/141050/1/m1.jpg

 Output Menu Type 2)

 https://i1.code.msdn.s-msft.com/angularjs-dynamic-menu-dc974920/image/file/141051/1/m2.jpg

 **Note: **This code can be used in our MVC View page or this code can be used in Shared>Layout.Cshtml so that the menu will be a common menu that can be used for all pages globally. Here we can see in the preceding that the same menu code has been added to the Layout.cshtm page. By this the menu will be added globally and can be accessed in all pages.

 https://i1.code.msdn.s-msft.com/angularjs-dynamic-menu-dc974920/image/file/141052/1/m5.jpg

More Information

We can extend this application depending on the requirements and add more functionality, like user management, menu management and and so on.This program was been created using Visual Studio 2013 We can also do the same with Visual Studio 2015 as per the requirement.

Tested Browsers: Chrome and Firefox. 

 You can download the Source Code from this link Download Source Code