将当前范围传递给 AngularJS 服务 [英] Passing current scope to an AngularJS Service

查看:28
本文介绍了将当前范围传递给 AngularJS 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将当前"$scope 传递给 AngularJS 服务是否正确?

Is it correct to pass the "current" $scope to an AngularJS service?

我的情况是我有一个 $service 知道它只被一个控制器使用,我想在 $service 方法本身中引用控制器的范围.

I'm in the situation where I've a $service knowing it's consumed by only one controller, and I'd like to have a reference to the controller's scope in the $service methods themselves.

这在哲学上正确吗?

或者我最好将事件广播到 $rootScope 然后让我的控制器监听它们?

Or I'd better to broadcast events to the $rootScope and then make my controller listen to them?

推荐答案

要让控制器知道异步发生时,请使用 Angular 承诺.

To let the controller know when something async happens, use Angular promises.

为了激发$apply,你不需要作用域,你可以调用$rootScope.$apply,因为在特定的调用它没有区别范围或在根中.

To provoke the $apply, you don't need the scope, you can call $rootScope.$apply, as there is no difference calling it in a specific scope or in the root.

关于变量读数,如果能收到参数就更好了.但是您也可以从范围中将其作为对象参数读取,但我会使用参数,这将使您的服务界面更加清晰.

Regarding the variable reading, it would be better if you received parameters. But you could also read it from a scope as an object parameter, but I would go with parameter, that would make your service interface much more clearer.

这篇关于将当前范围传递给 AngularJS 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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