-->

Google organization (org) chart using AngularJS



Introduction

Previously we have seen following articles about implementing google chart in asp.net application

but till now we have not created any google chart example in AngularJS application. Today I will show you how to implement google organization chart (Org chart) using AngularJS.

Just follow the following steps in order to implement "Google org chart using AngularJS".

Here In this article, I have used Visual Studio 2013

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Add a Database.

Now I will create a database for our application. As this is a tutorial project, I will add a database in our application, here in the app_data folder.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create 1 table in our database.

Now we have to create a table in our database for store data (hierarchical data).
You can see here in this below image, I have added a column ReportsTo. This field is for Whom the employee reports to. This field must contain each manager's unique identifier here EmployeeID. For the employee at the top of the organization chart, we will fill 0 (ZERO).


double click on the database under app_data folder  for open the database in server explorer > expand the database and Right click on Tables node > click on Add New Table >  here we will write schema of the table for the table we want to create > now click on Update button for create the table and then again click on Update Database button. 

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a javascript file, where we will write AangularJS code for creating an angular module, an angular controller, and an angular directive.

var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$http', function ($scope, $http) {
    //here http get method for get data from database
    $scope.chartData = [['Name','ReportsTo','tooltip']];
    $http.get('/home/getChartData').then(function (response) {
        var newobject = [['Name', 'ReportsTo', 'tooltip']];
        angular.forEach(response.data, function (val) {
            newobject.push(
                [
                    {
                        v: val.EmployeeID.toString(),
                        f: '<div class="customBox"><div>'+ (val.FirstName + ' ' + val.LastName) +'</div><div class="title">' + val.Title + '</div></div>'
                    },
                    (val.ReportsTo.toString() == "0" ? "" : val.ReportsTo.toString()),
                    (val.FirstName + ' ' + val.LastName)
                ]
                );

        })
        $scope.chartData = newobject;
    })
}])
app.directive('orgChart', function () {
    function link($scope, element, attrs) {
        var chart = new google.visualization.OrgChart(element[0]);
        $scope.$watch('chartData', function (value, oldvalue) {
            if (!value) {
                return;
            }
            var data = google.visualization.arrayToDataTable(value);
            var options = {
                'title': '',
                'allowHtml': true
            }
            chart.draw(data, options);
        })
    }
    return {
        link: link
    };
})
Here in our application, I will add a javascript file into Scripts folder.
If you don't already have Scripts folder in your application, please first add Scripts folder and then add a javascript file into this folder.
Go to solution explorer > Right click on "Scripts" folder > Add > new Item > Select Javascrip file under Scripts > Eneter file name (here in my application it is "myScripts.js") > and then click on Add button.

Step-6: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ngGoogleOrgChart.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

You can see here 1 MVC action Index already added. Now we will add a view for that Index action. 

Step-7: Add view for that(here Index action) action.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select "Empty" under Template dropdown  > > Add.
HTML Code
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <script src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart','orgchart']}]}"></script>
    <script src="~/Scripts/myApp.js"></script>
    <style>
        #chart table{
            border-spacing:0;
            border-collapse:separate;
        }
        #chart tr td{
            line-height:15px;
        }
        .title{
            color:red;
        }
        .google-visualization--orgchart-node-medium{
            font-size:13px;
        }
    </style>
</head>
<body ng-app="myApp">
    <div ng-controller="myController">  
        <h2>Google Organization chart using AngularJS</h2>
        <div id="chart" ng-model="chartData" org-chart="chartData" style="text-align:center">
            Please Wait...
        </div>
    </div>
</body>
</html>
Note: Don't forget to add jQuery library in your _Layout.cshtml page, add this below code
     <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>   

Step-8: Add an MVC action into HomeController for fetch data (hierarchical data) from the database and return as JSON result.

public JsonResult getProductCategories()
{
    List<Category> categories = new List<Category>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        categories = dc.Categories.OrderBy(a => a.CategortyName).ToList();
    }
    return new JsonResult { Data = categories, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Step-9: Run Application.

We have done all the steps. Now it's time to run the application. 

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.