角JS - 让服务在全球范围,从控制器和视图访问 [英] Angular JS - Make service globally accessible from controllers and view

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

问题描述

让我们说我们有以下服务:

  myApp.factory('FooService接口',函数(){...

然后,控制器,我会说:

  myApp.controller('FooCtrl',['$范围,FooService接口',函数($范围,FooService接口){...

两部分的问题是:


  1. 全球无障碍:如果我有100控制器以及所有需要访问该服务,我不想明确地注入它的100倍。 我怎样才能使服务全球可用?只有我可以在此刻想到的事情是从根范围内,这违背了目的内包装它。

  2. 从视野辅助功能:我怎样​​才能从视图中访问服务? 这篇文章建议从控制器内包装的服务。如果我去那个长度,看来我应该只是落实根范围内的功能吧?


解决方案

找到一个合理的解决方案。其注入引导方法(运行),并把它添加到根的范围。从那里将提供给所有控制器和视图。

  myApp.run(函数($ rootScope,$位置$ HTTP,$超时,FooService接口){
    $ rootScope.foo = FooService接口;
    ....

重读我上面提到的帖子,也没有说包装究竟......只是抽象的,所以我presume海报指的是同样的解决方案。

有关完整性,回答(1)然后

  myApp.controller('FooCtrl',['$范围',函数($范围){
    //从范围根范围继承
    $ scope.foo.doSomething();
    ...

和的答案(2)仅仅是:

  {{DoSomething的()}}

Let's say we have the following service:

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

Then, from a controller, I would say:

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

The two-part question is:

  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?

解决方案

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.

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

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

and the answer to (2) is simply:

{{doSomething()}}

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

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