gpt4 book ai didi

javascript - 当工厂可以做同样的事情时,为什么要使用 $rootScope 在 Controller 之间共享数据?

转载 作者:搜寻专家 更新时间:2023-11-01 05:29:47 26 4
gpt4 key购买 nike

我的理解是 $rootScope 是某种全局变量,允许它在 Controller 之间共享。工厂也可以做同样的事情。那么,为什么不使用工厂呢?什么时候应该使用 $rootScope,什么时候应该使用工厂,因为它们的用途几乎相同?

最佳答案

AngularJS FAQ 已经很好地回答了这个问题 here :

$rootScope exists, but it can be used for evil

Scopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.

Occasionally there are pieces of data that you want to make global to the whole app. For these, you can inject $rootScope and set values on it like any other scope. Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like ng-show just like values on your local $scope.

Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.

Conversely, don't create a service whose only purpose in life is to store and return bits of data.

关于javascript - 当工厂可以做同样的事情时,为什么要使用 $rootScope 在 Controller 之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461900/

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