How To Create Dynamic AngularJS Tabs In MVC

In this post we will see how to create AngularJS dynamics tabs in MVC application. As you all are aware, we have a tab control in AngularJS; here we are going to see how those tabs can be created dynamically with some dynamic data, this dynamic data can be fetched from the database. Here I have created some dynamic data accordingly for making this article easy-to-understand. We will be creating an AngularJS app, controller, and service to fetch the data from our MVC controller. Once that is done, we will format the data and assign it to the tab control. Sounds good? I hope you will like this article.

Download Source Code

Download the source code from here: Dynamic Angular JS Tabs In MVC.

 
Background

Recently I got a requirement to create a tab control in one of my AngularJS applications. Then I thought of creating the same dynamically according to user needs. This article is a demo of the same.

Using the code

Firstly, we will start with creating an MVC application. Open your visual studio, then click File, New, then Project. Name your project.

Now that our application is launched, please go ahead and install AngularJS in your project from NuGet packages. You can see some new CSS files and scripts have been added to our project. So the set up has been done. Now what we need to do is to move on to the coding part.

Create a controller

Now we can create a new controller, in my case I created a controller ‘HomeController.’ In my controller I am going to call a model action which will return some dynamic data. See the code below.

  1. public class HomeController: Controller  
  2. {  
  3.     //  
  4.     // GET: /Home/  
  5.     public ActionResult Index()  
  6.     {  
  7.         return View();  
  8.     }  
  9.     public JsonResult TabData()   
  10.     {  
  11.         Test t = new Test();  
  12.         var myList = t.GetData();  
  13.         return Json(myList, JsonRequestBehavior.AllowGet);  
  14.     }  
  15. }  

Here we have one ActionResult and one JsonResult which we are going to call AngularJS service. As you can see I am creating an instance of my model Test, now we will create our model class. Shall we?

Create Model

I have created a model class with the name Test. Here I am creating some data dynamically using a for loop and assign those values to a list. Please see the codes below.

  1. namespace AsyncActions.Models  
  2. {  
  3.     public class Test  
  4.     {  
  5.         public List < Customer > GetData()  
  6.         {  
  7.             try  
  8.             {  
  9.                 List < Customer > cst = new List < Customer > ();  
  10.                 for (int i = 0; i < 15; i++)  
  11.                 {  
  12.                     Customer c = new Customer();  
  13.                     c.CustomerID = i;  
  14.                     c.CustomerCode = "CST" + i;  
  15.                     cst.Add(c);  
  16.                 }  
  17.                 return cst;  
  18.             } catch (Exception)  
  19.             {  
  20.                 throw new NotImplementedException();  
  21.             }  
  22.         }  
  23.     }  
  24.     public class Customer  
  25.     {  
  26.         public int CustomerID  
  27.         {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public string CustomerCode  
  32.         {  
  33.             get;  
  34.             set;  
  35.         }  
  36.     }  
  37. }  

As you can see I am creating a list of type of customer. Is that fine? Now what is pending? Yes, a view.

Create a view

Right click on your controller and click add view, that will give you a new view in your view folder. Hope you get that.

So our view is ready, now we can do some codes in our view to populate our tab. Are you ready?

  1. <div ng-controller="tabController" class="sample tabsdemoDynamicTabs" layout="column" ng-cloak="" ng-app="tab">  
  2.     <md-content class="md-padding">  
  3.         <md-tabs md-selected="selectedIndex" md-border-bottom="" md-autoselect="">  
  4.             <md-tab ng-repeat="tab in tabs" ng-disabled="tab.disabled" label="{{tab.title}}">  
  5.                 <div class="demo-tab tab{{$index}}" style="padding: 25px; text-align: center;">  
  6.                     <div ng-bind="tab.content"></div>  
  7.                     <br>  
  8.                     <md-button class="md-primary md-raised" ng-click="removeTab( tab )" ng-disabled="tabs.length <= 1">Remove Tab</md-button>  
  9.                 </div>  
  10.             </md-tab>  
  11.         </md-tabs>  
  12.     </md-content>  
  13.     <form ng-submit="addTab(tTitle,tContent)" layout="column" class="md-padding" style="padding-top: 0;">  
  14.         <div layout="row" layout-sm="column">  
  15.             <div flex="" style="position: relative;">  
  16.                 <h2 class="md-subhead" style="position: absolute; bottom: 0; left: 0; margin: 0; font-weight: 500; text-transform: uppercase; line-height: 35px; white-space: nowrap;">Add a new Tab:</h2>  
  17.             </div>  
  18.             <md-input-container>  
  19.                 <label for="label">Label</label>  
  20.                 <input type="text" id="label" ng-model="tTitle">  
  21.             </md-input-container>  
  22.             <md-input-container>  
  23.                 <label for="content">Content</label>  
  24.                 <input type="text" id="content" ng-model="tContent">  
  25.             </md-input-container>  
  26.             <md-button class="add-tab md-primary md-raised" ng-disabled="!tTitle || !tContent" type="submit" style="margin-right: 0;">Add Tab</md-button>  
  27.         </div>  
  28.     </form>  
  29. </div>  

As you can see we are declaring our AngularJS controller and app name as follows.

  1. ng-controller="tabController" class="sample tabsdemoDynamicTabs" layout="column" ng-cloak="" ng-app="tab"  

Now we will add the needed reference to our view.

Add the style sheet references

  1. <link href="~/CSS/angular-material.css" rel="stylesheet" />  
  2. <link href="~/CSS/docs.css" rel="stylesheet" />  

Add styles for tabs

  1. <style>  
  2.     .tabsdemoDynamicTabs md-content  
  3.     {  
  4.         background-color: transparent !important;  
  5.     }  
  6.       
  7.     .tabsdemoDynamicTabs md-content md-tabs  
  8.     {  
  9.         border: 1px solid #e1e1e1;  
  10.     }  
  11.       
  12.     .tabsdemoDynamicTabs md-content md-tabs md-tab-content   
  13.     {  
  14.         background: #f6f6f6;  
  15.     }  
  16.       
  17.     .tabsdemoDynamicTabs md-content md-tabs md-tabs-wrapper  
  18.     {  
  19.         background: white;  
  20.     }  
  21.       
  22.     .tabsdemoDynamicTabs md-content h1:first-child  
  23.     {  
  24.         margin-top: 0;  
  25.     }  
  26.       
  27.     .tabsdemoDynamicTabs md-input-container  
  28.     {  
  29.         padding-bottom: 0;  
  30.     }  
  31.       
  32.     .tabsdemoDynamicTabs .remove-tab  
  33.     {  
  34.         margin-bottom: 40px;  
  35.     }  
  36.       
  37.     .tabsdemoDynamicTabs .demo-tab > div > div  
  38.     {  
  39.         padding: 25px;  
  40.         box-sizing: border-box;  
  41.     }  
  42.       
  43.     .tabsdemoDynamicTabs .edit-form input  
  44.     {  
  45.         width: 100%;  
  46.     }  
  47.       
  48.     .tabsdemoDynamicTabs md-tabs  
  49.     {  
  50.         border-bottom: 1px solid rgba(0, 0, 0, 0.12);  
  51.     }  
  52.       
  53.     .tabsdemoDynamicTabs md-tab[disabled]   
  54.     {  
  55.         opacity: 0.5;  
  56.     }  
  57.       
  58.     .tabsdemoDynamicTabs label  
  59.     {  
  60.         text-align: left;  
  61.     }  
  62.       
  63.     .tabsdemoDynamicTabs .long > input  
  64.     {  
  65.         width: 264px;  
  66.     }  
  67.       
  68.     .tabsdemoDynamicTabs .md-button.add-tab  
  69.     {  
  70.         transform: translateY(5px);  
  71.     }  
  72. </style>  

Add the JS references

  1. <script src="~/Scripts/angular.min.js"></script>  
  2. <script src="~/Scripts/angular-animate.min.js"></script>  
  3. <script src="~/Scripts/angular-route.js"></script>  
  4. <script src="~/Scripts/angular-aria.min.js"></script>  
  5. <script src="~/Scripts/angular-messages.min.js"></script>  
  6. <script src="~/Scripts/svg-assets-cache.js"></script>  
  7. <script src="~/Scripts/angular-material.js"></script>  
  8. <script src="~/Scripts/Module.js"></script>  

Here Module.js is the file where we are creating our AngularJS controller, Service, App. So can we go ahead and create those?

Create an app, controller, service in AngularJS

To add an app, controller, service in Angula JS, you need to add the codes as below.

  1. (function()  
  2.  {  
  3.     'use strict';  
  4.     var app;  
  5.     (function()  
  6.      {  
  7.         //create app  
  8.         app = angular.module("tab", ['ngMaterial''ngMessages''material.svgAssetsCache']);  
  9.         //create controller  
  10.         app.controller('tabController', function($scope, tabService)   
  11.         {  
  12.             var serv = tabService.getAll();  
  13.             serv.then(function(d)  
  14.             {  
  15.                 tabController(d.data, $scope);  
  16.             }, function(error)  
  17.             {  
  18.                 console.log('Something went wrong, please check after a while');  
  19.             })  
  20.         });  
  21.         //create service  
  22.         app.service('tabService', function($http)  
  23.         {  
  24.             this.getAll = function()  
  25.             {  
  26.                 return $http  
  27.                 ({  
  28.                     url: "/Home/TabData"//Here we are calling our controller JSON action  
  29.                     method: "GET"  
  30.                 });  
  31.             };  
  32.         });  
  33.     })();  
  34. })();  

As you can see once we get the data from the AngularJS service (tabService) to the controller (tabController). We are passing the data to a function named tabController. Below is the code for that function.

  1. function tabController(data, $scope)  
  2. {  
  3.     var tabsArray = [];  
  4.     for (var i = 0; i < data.length; i++)  
  5.     {  
  6.         tabsArray.push  
  7.         ({  
  8.             'title'"Customer ID: " + data[i].CustomerID,  
  9.             'content': data[i].CustomerCode + " The data you are seeing here is for the customer with the Custome rCode " + data[i].CustomerCode  
  10.         });  
  11.     }  
  12.     var tabs = tabsArray,  
  13.         selected = null,  
  14.         previous = null;  
  15.     $scope.tabs = tabs;  
  16.     $scope.selectedIndex = 0;  
  17.     $scope.$watch('selectedIndex', function(current, old)  
  18.     {  
  19.         previous = selected;  
  20.         selected = tabs[current];  
  21.     });  
  22.     $scope.addTab = function(title, view)  
  23.     {  
  24.         view = view || title + " Content View";  
  25.         tabs.push  
  26.         ({  
  27.             title: title,  
  28.             content: view,  
  29.             disabled: false  
  30.         });  
  31.     };  
  32.     $scope.removeTab = function(tab)   
  33.     {  
  34.         var index = tabs.indexOf(tab);  
  35.         tabs.splice(index, 1);  
  36.     };  
  37. }  

That’s all we created the AngularJS tabs dynamically. Shall we see the output now?

Output:

Dynamic Angular JS Tabs In MVC Figure 1
                                           Dynamic Angular JS Tabs In MVC

Dynamic Angular JS Tabs In MVC Figure 2
                                            Dynamic AngularJS Tabs In MVC 

Reference:

Conclusion:

Did I miss anything that you may think is needed? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Please see this article in my blog here.

Read more articles on AngularJS: