Thursday, November 5, 2015

AngularJS - Are Service object instances global or local?

Ref:- http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers#Whatarecontrollersandneedofng-controllerandng-modelinAngular

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.
function HitCounter()
{
       var i = 0;
        this.Hit = function ()
        {
            i++;
            alert(i);
        };
}
This “HitCounter” class object is injected in “MyClass” class as shown in the below code.
function MyClass($scope, HitCounter)
{
 $scope.HitCounter = HitCounter;
}
Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.
var app = angular.module("myApp", []); // creating a APP
app.controller("MyClass", MyClass); // Registering the VM
app.service("HitCounter", HitCounter); // Injects the object
Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.
So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.
When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.
If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

1 comment:

  1. Sain Bainuu,


    Gasping at your brilliance! Thanks a tonne for sharing all that content. Can’t stop reading. Honestly!


    I need to save documents in sql database in my application. using file upload and angularjs asp.net web api .

    Is there any sample code send to me.

    Awesome! Thanks for putting this all in one place. Very useful!


    Thank you,
    Irene Hynes

    ReplyDelete