Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is two-way databinding in AngularJS an antipattern?

AngularJS offers two-way databinding.

I built several AngularJS apps and found two-way databinding to be a powerful feature, that increased my productivity.

Recently however I come more and more across posts and articles that claim that two-way databinding is an antipattern.

Examples:

  • https://medium.com/este-js-framework/whats-wrong-with-angular-js-97b0a787f903#.py84tbylf
  • https://www.dotnetrocks.com/?show=1147
  • https://www.youtube.com/watch?v=DslsyqnyjQE
  • Angular2 two-way data binding

Most of the resources argue in favour of "Unidirectional Dataflow" like it is promoted by React/Flux.

Also Angular2 announced for some time that there will be no two-way binding... but the latest documentation shows that it is actually offering two-way databinding via ngModel again (implemented on top of property- and event-binding)

However I do not yet fully understand the problems that relate to two-way databinding in AngularJS.

Other client technologies (i.e. swing, eclipse-rcp, winforms, wpf ...) also offer two-way databinding, and I never stumbled over the claim that it is an anti-pattern ...

Is there a canonical example that easily illustrates the problems that might result from two-way databinding in AngularJS?

The video I linked above seems to hint that $scope.watch is the problem ... but the example can be implemented without $scope.watch by binding to a function exposed on the $scope.
If you avoid using $scope (i.e. using controller as), what problems remain with two-way databinding?

like image 305
jbandi Avatar asked Sep 07 '25 19:09

jbandi


1 Answers

In fact, the main problem with two-way data binding is performance.

When AngularJS was released (1), this feature was the foremost reason why the framework was much used by developers.

Without a line of code, you can make an element fully dynamic by changing its value from the model side or the view side, the value is changed everywhere the model is set.

In this feature, the most important tool is the watching, and it represents all the problem with two-way data binding.

As the application evolves, the number of watchers and watched elements increases.
Also, after a time, the application can become a big soup of watchers.
This will result in your application always watching elements and keeping up-to-date the elements at the inverse side, and that consumes a lot of resources from the browser.

This is why my recommendation is: Avoid watchers as much as possible.
They are almost never really necessary in a controller.

See also :

  • Effective strategies to avoid watches in AngularJS
  • The bad parts of AngularJS
  • Performances in large AngularJS applications

Hope it's more clear for you.

like image 67
chalasr Avatar answered Sep 10 '25 08:09

chalasr