角JS注入新的类实例 [英] Angular JS inject new instance of class

查看:99
本文介绍了角JS注入新的类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想注入类的实例。从这个线程,它看起来像服务回报新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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆