Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Saturday, December 5, 2015

Creating Services in Angular2.0

In an application,  service is a component which consists of business logic or set of individual functions. Services often served as loosely coupled modules.

If you are building an Angular2.0 application there are various ways to inject the service into your component. Service consumption in Angular2.0 application follows dependency injection principles. Component can be resembled to directives in Angular1.x. So if you component needs a service instance, then the service can be injected while constructing the component.

For example here I am creating a component named as Event component, following is the way the component can be accessed in HTML:


<event-component></event-component>

The Angular2.0 code for the above component written below:

@Component({

    selector: 'event-component',
    templateUrl:'eventcomp.html',
    styles: [],
    directives: []

})

class EventComponent {

  constructor(VenueService:VenueService,

  @Inject('App.config')config: config,food:FoodAndBeveragesService) {

    this.title=config.title;
    this.schedule=config.schedule;
    this.duration=config.duration;
    this.venueServiceInst=VenueService;
    this.booked=false;
    this.beveragesIncluded=food.beveragesIncluded;

  }

  bookVenue(){

    if(this.venueServiceInst.bookVenue()){
      this.booked=true;
    }
  }
}

The constructor in the above code has three services injected into it.


  • VenueService
  • FoodAndBeveragesService
  • config

While bootstrap of your component you can configure services for your component, as written below:


bootstrap(EventComponent,[VenueService,FoodAndBeveragesServiceProvider,
provide('App.config', {useValue:config})]);

The VenueService code is pretty simple, following is the code:


import {Injectable} from 'angular2/angular2';
@Injectable()
export class VenueService{
  bookVenue(){
    console.log('booking venue');
    return true;
  }
}


The above service is written in a separate typescript file. So the export notifies which class you want to expose for access from other files. The Injectable annotation says that the service is injectable.

The FoodAndBeveragesService code is as simple as above service, following is the code:


import {Injectable} from 'angular2/angular2';

@Injectable()
export class FoodAndBeveragesService{

beveragesIncluded:boolean;
  constructor(beveragesIncluded?:boolean){
  this.beveragesIncluded=beveragesIncluded; 
  }

  bookFoodAndBeverages(){

    return true;
  }
}

But while injecting there is a provider configured for it, to create a provider for the service, here is the code snippet for it:

let foodAndBeveragesServiceFactory = () => {
  var beveragesIncluded=true;
  return new FoodAndBeveragesService();
};

let foodAndBeveragesServiceDefinition = {
   useFactory: foodAndBeveragesServiceFactory,
   deps:[]
};

let FoodAndBeveragesServiceProvider = provide(FoodAndBeveragesService, foodAndBeveragesServiceDefinition);
The contrasting difference between the  injection of VenueService and FoodAndBeverageService is the creation of the service instance is in the control of it's corresponding factory method, so in the above factory creation we can change the invocation of the service instance creation as shown in the following code:

let foodAndBeveragesServiceFactory = () => {
  var beveragesIncluded=true;
  return new FoodAndBeveragesService(beveragesIncluded);
};
Now lets come to config service, this is how it's been created:

let config = {

  title: 'AngularJS Meetup',

  schedule:'Mon, 23rd Dec 2015',

  duration:'6'

};
So config is basically an object which can be injected in to any component. To inject it as it's written in the bootstraping of the component:

provide('App.config', {useValue:config})
And while injecting it in the constructor of the component we mention it as follows:

@Inject('App.config')config: config

So above are the ways to create and inject services in Angular2.0. Following is the working code base of the above examples.

Saturday, November 21, 2015

Creating a video player using Angular 2.0

The best way to learn Angular2.0 is to write components. So instead of writing tutorial I prefer to start creating components. In this post we will create a video player having custom control to show the usage of Angular2.0

Typescript and SystemJS are two dependencies requires for this example.

Please install Angular2.0 as mentioned in the below link:

https://angular.io/docs/ts/latest/quickstart.html

The following plunkr contains the codebase  for the component:

The full-screen feature might not work because of browser's restriction. However once you copy the codebase to your favorite editor and run it, the full-screen feature will work smoothly. All Functionalities have been tested in Safari, Chrome and Firefox browser.

Please fell free to comment on the component so that I can extend it to have more functionalities.






Sunday, February 22, 2015

AngularJS controller in-depth

Controller in an AngularJS application plays as a role of bridge between your model and view. There are certain best practices need to be followed while designing a controller for your application.

  • REST calls should not be invoked in controller(Use Services).
  • Any filtering of the data like changing the text as browser language changes should not be done in controller(Use Filters)
  • Controllers should not be used to act as a communicator between two different AngularJS modules(Use event emitters)

Following example shows how to write a controller("Controller as" Syntax):

HTML file


<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-app="testapp">
      <div ng-controller="utilcontroller as util">
        <input type="text" ng-model="util.name">
        <button ng-click="util.greeting()">Say Hii</button>
        <div>
          <b>{{util.nameWithGreetingMsg}}</b>
        </div>

      </div>

    </div>
  </body>

Javascript file(script.js mentioned in the HTML file)


angular.module("testapp", []).controller('utilcontroller', function() {

    this.greeting = function() {
   
    this.nameWithGreetingMsg = "Hello " + this.name;
  }
});


Constructor is a constructor function, in the above example utilcontroller  is the constructor function, so when we mention the ng-controller directive in the HTML, this constructor function get called and a new object gets created. In the above example the new object name is util.

Let's write without "controller as" syntax.

HTML file

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div ng-app="testapp">
    <div ng-controller="utilcontroller">
      <input type="text" ng-model="name">
      <button ng-click="greeting()">Say Hii</button>
      <div>
        <b>{{nameWithGreetingMsg}}</b>
      </div>

    </div>

  </div>
</body>
</html>

Javascript file(script.js mentioned in the HTML file)


angular.module("testapp", []).controller('utilcontroller', function($scope) {

  $scope.greeting = function() {

    $scope.nameWithGreetingMsg = "Hello " + $scope.name;
  }

});

In the above program all the properties and methods are attached to $scope.


Scope Inheritance

To achieve scope inheritance controllers can be used. It's very normal while creating an HTML view we assign different controllers at different view level. so for example in the below program:

<div ng-controller="vehiclecontroller as vehicle">
  <div ng-controller="carcontroller as car">
    No of wheels: <b>{{car.wheels}}</b>
    <button ng-click="vehicle.start()">Start Car</button>
  </div>
  <div ng-controller="bikecontroller as bike">
    No of wheels: <b>{{bike.wheels}}</b>
    <button ng-click="vehicle.start()">Start Bike</button>
  </div>
</div>

We have one parent controller and two child controllers,  the child controller are able to access the parent scope's data through referring the parent controller's name(vehicle.start). The 'start' method is defined in vehiclecontroller function:

angular.module("testapp", []).controller('vehiclecontroller', function() {
  
  this.start = function() {

    console.log("vehicle started");
  }

}).controller('carcontroller', function() {
  this.wheels = 4;
}).controller('bikecontroller', function() {
  this.wheels = 2;
});

$watch in controller

$watch is AngularJS is used to observe the scope properties, once the property's value  changes the callback function defined in the $watch executes.

Inside controller we write watchers(in case of controller as syntax):

controller('carcontroller', function($scope) {
  this.wheels = 4;
  this.gear="neutral";
  $scope.$watch(angular.bind(this,function(){return this.gear}),function(newVal,oldVal){
    console.log("Gear changed from"+ oldVal+ "to "+newVal);
  });


Note: More about angular.bind.


In case of without controller as syntax the $watch is pretty simple:
 $scope.$watch('gear',function(newVal,oldVal){
    console.log("Gear changed from"+ oldVal+ "to "+newVal);
  });


That's pretty much for controller's role inAngularJS app. In the upcoming post we will learn about FormController role in an application.



Sunday, July 27, 2014

Key points about AngularJS Directive and custom element using Polymer.

Creating custom element is achievable by creating a custom Directive in AngularJS. We can say it's one of the best feature of the framework. As Google's Polymer project is in hype for it's material design and web component based architecture, it also supports functionalities to create a custom component.

To create a directive in AngularJS:


To create a custom web component in Google Polymer:


Once you get a understanding both of these ways to develop a component we may conclude these are main key points to achieve each blocks of custom component:


Functionality In AngularJS In Polymer
Template of a custom element It supports writing template as well as loading template from a URL It supports writing template
Styling template and it's contents In template itself you can add styles and classes In template you can have "<style>" tags to describe different inline styling
Wrapping other HTML by custom component It provides ng-transclude as well as trancluseFunction to achieve this functionality Here it provides insertion point, which tells the browser where to render children
Writing JavaScript logic It can be written inside controller, compile and lining functions. It can be written inside "<script>" tag.


























Sunday, June 29, 2014

key binding on auto suggestion list in AngularJS




Following are the work flow steps:

1: Enter a value in the first text field
2: The suggestion list appears below the text box.
3: Up and Down key are used to navigate between items in the list.
   Selected item appears in gray color.
4: Press Enter key to select an item from the list.
5: Press tab to move to second field.
6: You can also use mouse to select one item from the list

Sunday, June 15, 2014

ng:repeat and radio button problems

We all know ng-repeat creates it's own scope for each repeated item. Take the following example

<html>
<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];

    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <div ng-repeat="item in nameList">{{item.name}}</div>
</body>
</html>



The above code actually creates two divs (one for each item in the nameList) and renders those with the content and the output would be
Lemon
John

If we try to do similar thing where we put radio buttons instead of divs it will create separate scope for each radio button.

Let's change our HTML to the below one:


<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];
      $scope.selectedItem = $scope.nameList[0];
    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <form>
    Select a name fom two names:
    <br/>
    <span ng-repeat="item in nameList">
    <input type="radio" name="name" ng-value="item" ng-model="selectedItem">{{item.name}}<br/>
  </span>
    <br/>The selected name:{{selectedItem.name}}
  </form>

</body>

</html>

Here is the Plunkr link:

Plunkr for above HTML

However if we select any radio button it does not change the selectedItem value of the scope, because it changes value of selectedItem of the new scope for span, to bind to the parent scope's selectedItem object we have to change the code to....

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];
      $scope.selectedItem = $scope.nameList[0];
    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <form>
    Select a name fom two names:
    <br/>
    <span ng-repeat="item in nameList">
    <input type="radio" name="name" ng-value="item" ng-model="$parent.selectedItem">{{item.name}}<br/>
  </span>
    <br/>The selected name:{{selectedItem.name}}
  </form>

</body>

</html>


The $parent refers to the parent scope so now we refer to the selectedItem object which is defined in our controller.

The above approach looks simple, however when the radio button goes under a transcluded directive  we need to refer something like $parent.$parent....... till we reach the main controller's scope.

Another approach would be doing this in event publish/subscribe pattern.
Here is the implementation:


<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script>
    angular.module("sampleapp", []).controller('samplecontroller', function($scope, $rootScope) {
      $scope.nameList = [{
        name: "Lemon"
      }, {
        name: "John"
      }];
      $scope.selectedItem = $scope.nameList[0];

      $scope.changehappened = function(data) {

        $rootScope.$emit('nameselected', data);
      };
      $rootScope.$on('nameselected', function(evt, data) {

        $scope.selectedItem = data;
      });
    });
  </script>

</head>

<body ng-app="sampleapp" ng-controller="samplecontroller">
  <form>
    Select a name fom two names:
    <br/>
    <span ng-repeat="item in nameList">
    <input type="radio" name="name" ng-value="item" ng-model="$parent.s" ng-change="$parent.changehappened(item)">{{item.name}}<br/>
  </span>
    <br/>The selected name:{{selectedItem.name}}
  </form>

</body>

</html>



Tuesday, June 3, 2014

dragging table rows in IE9

This post is regarding the rearranging rows in a table by doing drag and drop( my previous post Rearranging rows by Drag and Drop ). The reason it does not work in IE 9(Internet explorer version 9 ) is  because of  the browser does not support draggable attribute for tr tag. So to make the reordering work by drag and drop  is by adding and 'a' tag as the first column which basically work as an anchor to do drag the row.

As IE9 support draggable attribute on 'a' then the browser can understand and do drag the particular row.
In the help of polyphil we can detect the browser and add draggable attribute to the correct tag:

1: IE9:  a tag (<a draggable="true"></a>)
1: Other browsers(Chrome and Firefox):  tr tag(<tr draggable="true">)

Please check this fiddle to know how to check the browser version and accordingly make the required element draggable.

JSFiddle example

Wednesday, April 16, 2014

An angular table directive having reordering of rows feature by doing drag and drop

 I have created one table directive which has support for row reordering in drag and drop way.
 This table directive named as angTable uses two other directive draggable and droppable directive.

  Checkout the column reordering part

The angTable directive creates one table having column and rows derived from a configuration.This configuration is nothing but an object having two attributes 'head' and 'data'.

head: Array having the column header labels.
data:  Array having objects as rows

To add the drag and drop feature for the columns, draggable and droppable attribute directives have been used with their required parameters.Please check the readme.md file in the below Plunker link.

Note:To give feedback image while dragging occurs there are two other subtable in the directive where one table is on top of the other table using z-index.The top table coloring  scheme is white so that it can hide the table below it, that way the table which is at bottom in the layer having less z-index is hidden from the user but displayed to the browser, so when we drag any column of the actual table the below subtable is actually getting dragged.

http://plnkr.co/iy63pZ

Wednesday, February 19, 2014

angular.identity example

Here is a simple use of angular.identity example, angular.identity helps to write functional style code.below is the documentation:

API Doc for angular.identity

As to showcase the use of this, here we have a simple angular application which displays square value and multiplied by 2 value of a number. For example:

Input Value:5
Square:25
Multiply By two: 10

To achieve this,  I have created two functions:

$scope.square = function (n) {
  return n * n
};

$scope.multplybyTwo = function (n) {
  return n * 2};

In addition to this, I have a separate helper function which calls these function passing it's first argument.

$scope.givemeResult = function (fn, val) {
  return (fn || angular.identity)(val);
};

Then  the givemeResult function may be invoked in the below fashion:

$scope.initVal = 5;
$scope.squareResult = $scope.givemeResult($scope.square, $scope.initVal);
$scope.intoTwo = $scope.givemeResult($scope.multplybyTwo, $scope.initVal);


You may visit the Plnkr.

Sunday, February 16, 2014

An example of use of Protractor with Mocha and Chai for an Angular applicaion

Protractor is for end to end or integration testing of an Angular JS application. Its from the user perspective testing the application. Don't get confused with Karma, Karma is for unit testing.

To make it more clear a directive or a module can be tested with Karma, but to test the whole application from end to end we need Protractor like framework.

Protractor is a wrapper around WebdriverJS. If you have heard about Selenium, then Selenium 2.0 is actually a combination of Selenium 1.0 and WebDriver API. Please follow the link to know more about it:
http://docs.seleniumhq.org/projects/webdriver/

Mocha is a Javascript test  framework developed in Node.js framework:
http://visionmedia.github.io/mocha/

Chai is an assertion library which provides lots of functionalities to create BDD/TDD based tests.It provides several libraries like Should, Assert and Expect. 
http://chaijs.com/

I can explain each of these libraries, but this is not scope of my post, here I will explain how to install each of these and create a sample test file and run it successfully. Follow the steps for it:
First install Node.js then follow these steps:


1. npm install -g protractor

2. web-driver manager update

3. npm install -g mocha

4. npm install chai

5. npm install chai-as-promised

Lets create a simple AngularJS application which we will test:

main.js
----------
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
    $scope.myName = "John";
});
main.html
------------

<!doctype html>
<html>
<head>
    <title>SampleApp</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
    <script src="main.js"></script>
</head>
<body>
<div ng-app="my-app">
    <div ng-controller="my-ctrl">
        <div>{{myName}}</div>
    </div>
</div>
</body>
</html> 


Now let's create the test configuration for protractor:

protractortest_conf.js
---------------------------

exports.config = {
    framework: 'mocha',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['e2e_test.js']
}

Let's create the actual test script:

e2e_test.js
---------------------------
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
//Give the URL to the actual URL where your Angular app is runningbrowser.get('http://127.0.0.1:9000/#/main);
var name = element(by.binding('myName'));
expect(name.getText()).to.eventually.equal('John');


To run the test please use the following command:

 protractor protractortest_conf.js


Now you should able to see the results of the end to end testing of the application.     

Sunday, February 9, 2014

Introduction to Transclusion of directives in AngularJS

This is an introduction to the transclusion part of directives in AngularJS. In order to make it more simpler, I have created one directive:

http://plnkr.co/edit/T2hh9d?p=preview

which uses couple of key use cases(mentioned below) of transclusion.

ng-transclude:  Rendering transcluded content. 
transcludeFn:   Constructor Function to modify the transcluded content with or without new scope.

By definition transclusion is the inclusion of document or part of the document into another document by reference.(From Wikipedia)

In case of AngularJS transclusion is used in similar fashion but we have more control on the transcluded content. If you are creating a directive which basically acts as an wrapper for it's child contents, and the content can be anything.Then transclusion should be your approach.

 Consider the below directive:
    
<org-v-card>

    <h4>{{firstName}} {{lastName}}</h4>

    <h5>Designation: {{jobtitle}}</h5>

    <h5>Company: {{company}}</h5>

    <h5>Phn no: {{phn}}</h5>

    <h5>Email: {{email}}</h5>

</org-v-card>

In the above example org-v-card is an user defined directive which acts as wrapper for it's child contents(one h4 and four h5 elements ).

Lets look into the template part  of the org-v-card directive.

<div class="vcard">
    Quick Info:<span ng-transclude></span>
</div>

In the above example to access all the child content(In this example one h4 and four h5 elements) and to render  it we are using <span ng-transclude></span>. The directive ng-transclude provided by AngularJS renders the child contents of the parent directive(In this example org-v-card).

Lets look into the controller:

var theApp = angular.module('myApp', []);

theApp.controller('myCtrl', function ($scope) {

  $scope.firstName = "Mike";
  $scope.lastName = "Logan";
  $scope.jobtitle = 'Consultant';
  $scope.company = 'BCA Corp.';
  $scope.phn = '080-22116677';
  $scope.email = 'mlogan@bca.com';
});


theApp.directive('orgVCard', ['$compile',
  function ($compile) {
    return {
      restrict: 'E',
      transclude: true,
      templateUrl: 'vcardtemplate.html',
      replace: true,
      link: function (scope, iele, attr, controller, transcludeFn) {
        /**        
         * Modify the  transcluded content with a new scope and return the cloned content        
       */     


   var modifyTranscludeContent = function (clonedelem, newscope) {

          newscope.firstName = "Jane";
          newscope.lastName = "King";
          newscope.jobtitle = 'Manager';
          newscope.company = 'BCA Corp.';
          newscope.phn = '080-22116678';
          newscope.email = 'jking@bca.com';
          clonedelem.scope = newscope;
          angular.element(clonedelem[0]).css('font-weight', 'bold')
            .css('color', 'red');
        };

        /**         
        * It shows the top most div        
        */        
        console.log(iele);
        /**         
         * Get the modified transcluded content      
         */        
        var transInstance = new transcludeFn(scope.$new(), modifyTranscludeContent;

        iele.append('Reports to:')
        /**         
         *Render the cloned content compiled with new scope values         
        */       
        iele.append(transInstance);


      }

    };

  }
]);

In the above script we are creating following scope variables:
 firstName, lastName, jobtitle, company, phn and email.

In the directive we are giving transclude:true, which means this directive can act as wrapper for it's child elements.

In the link function we are passing transcludeFn as an parameter, this function takes two parameters:

scope.$new: [Optional]A newly generated scope which is applicable only to the transcluded   content not to the directive.
modifyTranscludeContent:  This function(defined in the link function ) as defined above it accepts two parameters , clonedelement and the scope.

clonedelement :   The cloned element of the transcluded  content. Which  also get returned by the transcludeFn.
scope: The scope for the cloned elements.If no values  passed for this then the scope assigned to the directive will be considered as the value.

Inside  modifyTranscludeContent we are assigning different values to properties  of the scope passed to the  function  and assigning that scope to the clonedelement.

Consider the below line:

var transInstance = new transcludeFn(scope.$new(), modifyTranscludeContent);

transInstance is basically the cloned content after assigning the new scope to it. So now all the child content will render values which are assigned inside the transcludeFn.

In  the last line we are appending the cloned contents  to the parent directive.





Friday, February 7, 2014

An angular table directive having reordering of column feature by doing drag and drop

 I have created one table directive which has support for column reordering in drag and drop way.
 This table directive named as angTable uses two other directive draggable and droppable directive.

 Checkout the reordering of rows part

The angTable directive creates one table having column and rows derived from a configuration.This configuration is nothing but an object having two attributes 'head' and 'data'.

head: Array having the column header labels.
data:  Array having objects as rows

To add the drag and drop feature for the columns, draggable and droppable attribute directives have been used with their required parameters.Please check the readme.md file in the below Plunker link.

Note:To give feedback image while dragging occurs there are two other subtable in the directive where one table is on top of the other table using z-index.The top table coloring  scheme is white so that it can hide the table below it, that way the table which is at bottom in the layer having less z-index is hidden from the user but displayed to the browser, so when we drag any column of the actual table the below subtable is actually getting dragged.



http://plnkr.co/KvJglc



Sunday, December 15, 2013

Example of Scope hierarchy in Angular JS

Angular JS has a $scope object which is mostly used to expose the domain model, model or domain level properties are assigned to $scope and can be accessed in view as well as controller.

In a single application we can have multiple controllers and each controller can refer to their own instance of $scope object, parent scope as well as $rootScope which is parent most scope of an application.$rootScope is created when the application bootstraps.

In the below example I have 2 controllers for my application, one is mainController and other one is named as subController. subController has a child controller named as childController.

MainController has one property named as Mngname, and it assigns a property named compayName  to it's parent scope which is nothing but $rootscope.

SubController has one property named as amName.

ChildController takes $rootScope along with $scope as it's inputs, it has one property named empName, it creates and assigns  one property of it's parent scope i:e, scope of SubController named as dept. It creates another property comp which holds the value of companyName property of $rootScope.


<!DOCTYPE html>
<html>
<head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/
angular.js"></script>
    <script>
        var  mainController=function($scope)
        {
            $scope.MngName='Jade';
            $scope.$parent.companyName='Mcommerce';
        }
        var  subController=function($scope)
        {
            $scope.amName='Jane';
            $scope.childController=function($scope,$rootScope)
            {
                $scope.empName='Scott';
                $scope.$parent.dept='Sales';
                $scope.comp=$rootScope.companyName;

            }

        }
         var appVar=angular.module('ScopeTest',[]);
    </script>
    <title>Angular scope chain</title>
</head>
<body ng-app="ScopeTest">
   <div ng-controller="mainController">
        <table title="ParentTable" border="5px">
            <caption>Level1</caption>
            <tr>
                <td>Manager Name</td>
            <td>{{MngName}}</td>
            </tr>
            <tr>
                <td>
            <table border="4px" ng-controller="subController">
                <caption>Level2</caption>
                <tr>
                <td>Associate Manager Name</td>
                   <td>{{amName}}</td>
                </tr>
                <tr>
                    <td>Reporting To</td>
                    <td>{{MngName}}</td>
                    </tr>
                <tr>
                    <td>Department Assigned at Employee Level</td>
                    <td>{{dept}}</td>
                </tr>
                <tr>

                    <td>

                        <table border="3px" ng-controller="childController">
                            <caption>Level3</caption>
                            <tr>
                                <td>Employee Name</td>
                                <td>{{empName}}</td>
                            </tr>
                            <tr>
                                <td>Comp</td>
                                <td>{{comp}}</td>
                            </tr>


                        </table>
                    </td>
                </tr>
            </table>
                </td>
            </tr>
        </table>

   </div>

</body>
</html>