gpt4 book ai didi

javascript - Angular JS - 使服务可以从 Controller 和 View 全局访问

转载 作者:IT王子 更新时间:2023-10-29 03:21:53 26 4
gpt4 key购买 nike

假设我们有以下服务:

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

然后,从 Controller ,我会说:

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

两部分的问题是:

  1. 全局可访问性:如果我有 100 个 Controller 并且都需要访问该服务,我不想明确地注入(inject)它 100 次。 我怎样才能使该服务在全局范围内可用?目前我唯一能想到的就是将它从根范围内包装起来,这违背了目的。
  2. View 的可访问性:如何从 View 中访问服务? This post建议从 Controller 内包装服务。如果我要讲到那个长度,我似乎应该只在根范围内实现功能?

最佳答案

找到了合理的解决方案。将其注入(inject) Bootstrap 方法(运行),并将其添加到根范围。从那里它将对所有 Controller 和 View 可用。

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

重新阅读我上面提到的帖子,它并没有准确地说“包装”......只是“抽象”,所以我认为发帖人指的是同一个解决方案。

为了完整起见,(1) 的答案是:

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

(2) 的答案很简单:

{{doSomething()}}

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

@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

关于javascript - Angular JS - 使服务可以从 Controller 和 View 全局访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14571714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com