AngularJS Antipatterns and Pitfalls
nathanleclaire.com
nathanleclaire.com
For example, if you are polling for new data, it is MUCH cleaner to broadcast the event and let each directive react and change their own state. In other words, each directive should be in charge of their own state. It is not the poller's responsibility to understand who's state that it needs to mutate.
Events seem the perfect fit for pub/sub like you describe where there is a one to many relationship, but the pattern does seem abused by people who use it for a one to one communication between parts of the code. Calling it an anti-pattern is perhaps a bit too harsh and detracts from the valid uses. Though, I am glad the author brought it up as too many events in the system can make it challenging to reason about.
`on-select=handleSelection( selectedItem )` or something.
When it comes to controllers, I only have a few rules:
1. Never, EVER use $scope.$digest or $scope.$apply in any controller method. If you find yourself needing this, then you're missing a call in a spot higher up the stack ( event handler, websocket callback, etc.. ).
2. $timeout is acceptable if you legitimately need a delay - don't use it for control flow, ever. $evalAsync can be useful for coalescing multiple calls to a function into one during a digest cycle.
3. Minimal DOM manipulation. I will not say there's never a use case for DOM manip, but it should not be your first instinct most of the time. If it is, then take a step back and grab some coffee, go for a walk, and then look again. Often times, I'll use a variable instead and add a watcher on it in my directive to do the DOM manip. One can argue that it's needless overhead having the watcher, however I feel it's more in the spirit of Angular and does not contribute excessive overhead. If it does, then you can start making optimizations in the future after it's been proven that they're actually a problem.