微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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?具体注意性能部分。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐