Angularjs: How can I pass variables between controllers?
Best way to exchange data between controllers in AngularJS is to use a service. Below is a boilerplate you can easily adapt to your needs.
This setup lets you effortlessly read, write, and modify shared variables in your controllers by injecting the SharedVars
service.
Bind to Variables, not Trouble
Mind the dot in your binds! Functionality can become compromised if you forget to use a single dot in your bindings. This will guard against child scopes inadvertently creating properties on the parent scope, thus bypassing prototype-related concerns.
Even though $rootScope
might seem as a universal remedy, it often leads to coupling issues and debug nightmares due to unintentional cluttering of the scope. Here is where services or factories play their part in preserving reusability and modularity.
Building Factories Faster than Elves
You can use factories for the same purpose while giving you the benefit of lazy instantiation, or in layman terms, it sets up your shared data only when it's needed first. No wastage of memory!
Beware that factories offer an extra layer of control and are suitable for more complex application architectures compared to services.
Communicating Controllers through Event
The $broadcast, $emit, and $on methods can be used to send updates about data changes to other parts of your application in an event-driven manner.
However, such heavy use of events can introduce complexities to your unfamiliar Angular code. So, think twice before deciding the path of events.
Code Style Tips and Your Sanity
Here are some instructor-grade best practices:
- Object properties: Bind to object properties to prevent child scopes from overshadowing parent scopes.
- Global data: Use
$root
sparingly. It's the telltale sign of global data which should be an exception, not a norm. - Clarity: Invest time in commenting and documenting. They make your application easier to maintain and describe how data sharing is performed.
- Efficiency: For complex cases, hashtables within services can help manage states and references efficiently.
Was this article helpful?