Angular JS inject new instance of class

前端 未结 3 1282
情歌与酒
情歌与酒 2021-02-20 08:28

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/angul

3条回答
  •  独厮守ぢ
    2021-02-20 09:07

    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.

提交回复
热议问题