AngularJS使用$rootScope作为数据存储

我有一个想法,我的AngularJS应用程序,我很好奇,如果AngularJS社区会考虑这样做这个方法

总之,我连接到一个数据API,并在页面显示我的结果。我创建了一个角度服务,在$ rootScope.DataStore上创建一个数据存储。我还有一个服务方法,用从API端点返回的数据更新DataStore。如果我使用DataStore.update(‘products’)从我的控制器中请求“产品”API端点,这将更新$ rootScope.DataStore.products与我的产品数据。现在,在view / partial中,我需要做的是说ng-repeat =“DataStore.products中的产品”来显示我的数据,而不管我在什么控制器范围。因此,本质上我的DataStore是我唯一的真理来源。

我觉得从这种方法获得的是容易遵循语义和最小控制器编码。所以,任何时候DataStore更新,绑定到DataStore的任何东西也会得到更新。

这会给$ rootScope的摘要周期带来太多的负担,还是这只是一个奇怪的方式呢?或者是一个完全真棒的方式? :)欢迎任何意见。

这个问题在 AngularJS FAQ引用:

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.

看来,团队鼓励使用$ rootScope这种方式,与这个警告:

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.

这不会对$ digest循环(它实现基本的脏检查来测试数据突变)加载太多,这不是一个奇怪的方式来做事情。

编辑:有关性能的更多详细信息,请参阅此答案从Misko(AngularJS dev)这里在SO:AngularJS : How does databinding work?具体注意性能部分。

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...