Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - Angular use root scope vs services to share data

I have been reading wrox angular book. Inside the book the author describes that a method of sharing data between controllers is to

  1. Have a property on the root scope
  2. Update that property on the root scope
  3. Broadcast the fact that the property was updated
  4. All children scopes that need to know , will listen for the broadcast.

as opposed to expose an object on a Service and letting angular's two way databinding do all the heavy lifting. Why would anyone go with the 'root scope publish/subscribe' methodology, instead of exposing an object on the service?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's interesting question.

First we should consider differences on various levels:

  • Scope

    • in case of $rootScope we define variable in global scope
    • in case of shared services we can inject this service to controllers that really use this value
  • Extensibility

    • $rootScope - we have limited options to add additional logic to work on this value (we can define another global function)
    • shared services - we are free to define any kind of logic
  • Encapsulation

    • $rootScope - all object defined in $rootScope would be visible in all modules
    • shared services - we can decide what is visible and what is not
  • Modularity

    • $rootScope - global variables is not places in module spaces
    • shared services - service is a separate module for application
  • Maintaining

    • $rootScope - it's very hard to find which components use our $rootScope variable.
    • shared services - we can see which services we use and we can find in which component we use this service
  • Binding

    • $rootScope - it is easy to setup two-way binding in several controllers on one variable in $rootScope
    • shared services - could be tricky to enable two-way binding

In my opinion this is only useful for make really global variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...