0 votes
in Angular by
Are Service Object Instances Global or Local?

1 Answer

0 votes
by

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.

JavaScript

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.

HTML

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 HitCounter instance.

HTML

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 two div tags 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.

Image 16

If you execute the above code, you will see counter values getting incremented even if you are coming through different controller instances.

Related questions

0 votes
asked Dec 31, 2023 in Angular by DavidAnderson
0 votes
asked Dec 31, 2023 in Angular by DavidAnderson
...