Angular JS - 使服务可从控制器和视图全局访问 [英] Angular JS - Make service globally accessible from controllers and view

查看:21
本文介绍了Angular JS - 使服务可从控制器和视图全局访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下服务:

myApp.factory('FooService', function () { ...

然后,对于控制器,我会说:

Then, from a controller, I would say:

myApp.controller('FooCtrl', ['$scope', 'FooService', function ($scope, FooService) { ...

分为两部分的问题是:

  1. 全局可访问性:如果我有 100 个控制器并且都需要访问该服务,我不想显式注入 100 次.我怎样才能使服务在全球范围内可用?目前我唯一能想到的是从根范围内包装它,这违背了目的.
  2. 视图中的可访问性:如何从视图中访问服务?这篇文章 建议从控制器内部包装服务.如果我要达到这个长度,似乎我应该直接在根范围内实现功能?
  1. Global Accessibility: If I have 100 controllers and all need access to the service, I don't want to explicitly inject it 100 times. How can I make the service globally available? Only thing I can think of at the moment is wrapping it from within the root scope, which defeats the purpose.
  2. Accessibility from view: How can I access the service from within the view? This post suggests wrapping the service from within the controller. If I am going to that length, seems I ought to just implement the functionality right on the root scope?

推荐答案

找到了合理的解决方案.将其注入引导方法(run),并将其添加到根作用域.从那里它将可供所有控制器和视图使用.

Found a reasonable solution. Inject it into the bootstrap method (run), and add it to the root scope. From there it will be available to all controllers and views.

myApp.run(function ($rootScope, $location, $http, $timeout, FooService) {
    $rootScope.foo = FooService;
    ....

重新阅读我上面提到的帖子,它没有完全说包装"……只是抽象",所以我认为海报指的是相同的解决方案.

Re-reading the post I mentioned above, it didn't say "wrap" exactly... just "abstract", so I presume the poster was referring to this same solution.

为了彻底,(1) 的答案是:

For thoroughness, the answer to (1) is then:

myApp.controller('FooCtrl', ['$scope', function ($scope) { 
    // scope inherits from root scope
    $scope.foo.doSomething();
    ...

(2)的答案很简单:

{{doSomething()}}

添加克里斯托弗的评论以确保它被看到:

Adding Christopher's comment to make sure it's seen:

@rob - 根据最佳实践,应该注入工厂到需要使用它的控制器,而不是在根范围内.正如所问,第一个问题实际上是反模式.如果你需要工厂100次,你注射100次.这几乎没有任何额外的缩小后的代码,并清楚地说明工厂的使用位置,它使测试这些控制器变得更容易(也更明显)使用模拟,通过将所需的工厂全部列在函数签名.– Christopher WJ Rueber 2013 年 11 月 25 日 20:06

@rob - According to best practices, the factory should be injected in to the controllers that need to use it, rather than on the root scope. As asked, question number one actually is the antipattern. If you need the factory 100 times, you inject it 100 times. It's barely any extra code when minified, and makes it very clear where the factory is used, and it makes it easier (and more obvious) to test those controllers with mocks, by having the required factories all listed in the function signature. – Christopher WJ Rueber Nov 25 '13 at 20:06

这篇关于Angular JS - 使服务可从控制器和视图全局访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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