Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS inject new instance of class

Tags:

angularjs

I want to inject instances of a class. From this thread it looks like services return new serviceArgFunction, which is what I want. https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/VxECXKbn3gsJ

But I can't seem to get it to work. For some reason, my two instances of share state. Can anyone help me figure out what I'm doing wrong? http://jsfiddle.net/kTjMy/5/

var Klass = function() {
    this.count = 0;
    this.getAndIncCount = function() {
        this.count += 1;
        return this.count;
    };
};

app.service('service', Klass);
like image 870
will Avatar asked Nov 29 '12 06:11

will


People also ask

How do I create a new instance of a component?

Click and drag the component into the canvas to create an instance of that component.

What is $inject in AngularJS?

$injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.


2 Answers

To make it clear I created a little Plunker.

It has a Service and a Factory. Service and Factory have a value and setters and getters.

Both are injected into Controllers A and B. If You change the value of the Service in Controller A, this change takes also place in Controller B, because the service is a Singleton.

But when You change the value in the Factory in the Controller B, this affects only B because the change takes only place in the instance that is created in B.

Enjoy!

like image 119
Maximilian Eberl Avatar answered Nov 01 '22 18:11

Maximilian Eberl


You can use a factory that returns the constructor for your class:

app.factory('myKlass', function() {
  return Klass
});

Even more simply, if Klass is defined elsewhere, you can use value:

app.value('myKlass', Klass);

Either way, inject it as normal.

function CtrlA($scope, myKlass)
{
  new myKlass();
}

See this jsFiddle.

[Edit] See also this Google Groups post and this associated example.

like image 42
Michelle Tilley Avatar answered Nov 01 '22 18:11

Michelle Tilley