Angularjs 范围之外的服务功能 [英] Service functions outside Angularjs scope

查看:26
本文介绍了Angularjs 范围之外的服务功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angularJS 中创建了一个使用 btford.socket-io 模块与服务器交互的服务.由于在服务中我已经实现了一些我目前在 angular 内部使用的 API,但是对于应用程序的后续扩展,我还需要在 angular 范围之外访问这些 API.这样将来就可以调用该函数,而无需创建控制器和其他东西.

I have created a service in angularJS that uses btford.socket-io module to interact with the server. Since in the service I have implemented some API that I use inside angular at the moment, but for later extension of the application I also need to give access to these API outside angular scope. So that in future one could just call the function without having the need to create controller and other stuff.

目前我为控制器做了这个

At the moment I did this for a controller

var myController = angular.element($('body')).scope().myController;

通过将整个控制器保存在一个范围变量中.我想知道是否可以对服务做同样的事情.

by saving the whole controller inside a scope variable. I was wondering if it would be possible to do the same with a service.

推荐答案

怎么样:

angular.element(document.body).injector().get('MyService');

通常不是好的做法.但有时它需要.

Typically not good practice. But sometimes its needed.

注意:document.body 是你的 Angular 应用程序安装到的元素

Note: document.body is the element Your angular application is mounted to

您可能会考虑的另一件事是通过工厂关闭"带有 angular 的外部 api.

Another thing you might consider is 'closing' external api with angular via a factory.

  • 例如.从角度工厂返回您的全局或命名空间类或 API.

这基本上就是 angular 为您所做的.但是,您不必先在 angular 内部创建引用并提取它,而是在外部创建它,并将其注册为 DI 作为工厂或值.

This is essentially what angular does for you. But instead of creating the reference inside angular first and having to extract it, you'd create it outside, and register it with DI as a factory or value.

这篇关于Angularjs 范围之外的服务功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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