angular.injector在每次调用时返回新的服务实例

时间:2016-04-06 02:27:38

标签: javascript angularjs

created a simple plunk that demonstrates the issue

我需要从外角调用服务。

当我使用

angular.injector(['ng', 'MyModule']).get('MyService')

每次调用时我似乎都会获得一个新实例,或者至少表现得如此。在插件中,注意"增量"按钮调用相同的服务实例,而不是通过"呼叫通过注入器"的工作原理。

我一直在敲我的头几个小时,尝试了各种各样的东西,并阅读了许多明显相关的帖子,但无济于事。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

更改

angular.element('[ng-app]').injector().get('MyService').inc();

select d.Name as DrawerBox
     , dt.Name as DrawerBoxType
     , di.Inches as Inches
     , isnull(dbc.Value, dc.Value) Value      
from DrawerBox_C dc
join DrawerBox d
  on d.DrawerBoxId = dc.DrawerBoxId
join DrawerBoxInches  di
  on di.DrawerBoxInchesId = dc.DrawerBoxInchesId
join DrawerBoxType dt
  on dt.DrawerBoxTypeId = dc.DrawerBoxTypeId
left join dbo.DrawerBox_Bid_C dbc
  on dbc.DrawerBox_C_Id = dc.DrawerBox_C_Id
  and dbc.BidId = 1

第一个创建新注射器的实例。 angular中的每个注入器都有自己的服务和工厂实例。第二个获取现有的进样器实例。

此外,要使用angular.element选择DOM元素,需要包含jQuery。 Here是修改后的插件。

答案 1 :(得分:1)

此行为的原因是您没有获取范围的Injector实例,只是因为您将callViaInjector按钮放在ng-app之外。

虽然服务是角度的单例,但它们只是指定范围的单例。

请注意,如果将callViaInjector放在ng-app中,您将看到它的行为相应。