角JS注入新的类实例 [英] Angular JS inject new instance of class
问题描述
我想注入类的实例。从这个线程,它看起来像服务回报新serviceArgFunction,这就是我想要的。 <一href=\"https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/VxECXKbn3gsJ\">https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/VxECXKbn3gsJ
但我似乎无法得到它的工作。出于某种原因,我的份额州的两个实例。谁能帮我找出我在做什么错?
http://jsfiddle.net/kTjMy/5/
VAR克拉斯=功能(){
this.count = 0;
this.getAndIncCount =功能(){
this.count + = 1;
返回this.count;
};
};app.service('服务',克拉斯);
您可以使用一个工厂,返回构造类:
app.factory('myKlass',函数(){
克拉斯回报
});
更简单,如果克拉斯
在别处定义,你可以使用值
:
app.value('myKlass',克拉斯);
无论哪种方式,注入它是正常的。
函数CTRLA($范围,myKlass)
{
新myKlass();
}
请参阅此的jsfiddle 。
参见这个谷歌网上论坛帖子并的this相关例子。
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);
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.
这篇关于角JS注入新的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!