Mastering Web Application

(Rick Simeone) #1

Angular Zen


Two-way data binding

Rendering a template is straightforward with AngularJS; the framework shines when
used to build dynamic web applications. In order to appreciate the real power of
AngularJS, let's extend our "Hello World" example with an input field, as shown in
the following code:


<body ng-app ng-init="name = 'World'">
Say hello to: <input type="text" ng-model="name">
<h1>Hello, {{name}}!</h1>
</body>

There is almost nothing special about the HTML tag apart from the additional
ng-model attribute. The real magic happens as soon as we begin to type text into the


field. All of a sudden the screen gets repainted after each keystroke, to reflect
the provided name! There is no need to write any code that would refresh a template,
and we are not obliged to use any framework API calls to update the model. AngularJS
is smart enough to detect model changes and update the DOM accordingly.

Most of the traditional templating system renders templates in a linear, one-way
process: a model (variables) and a template are combined together to produce a
resulting markup. Any change to the model requires re-evaluation of a template.
AngularJS is different because any view changes triggered by a user are immediately
reflected in the model, and any changes in the model are instantly propagated to
a template.


The MVC pattern in AngularJS


Most existing web applications are based on some form of the well-known
model-view-controller (MVC) pattern. But the problem with the MVC is that it
is not a very precise pattern, but rather a high-level, architectural one. Worse yet,
there are many existing variations and derivatives of the original pattern (MVP
and MVVM seem to be the most popular ones). To add to the confusion, different
frameworks and developers tend to interpret the mentioned patterns differently.
This results in situations where the same MVC name is used to describe different
architectures and coding approaches. Martin Fowler summarizes this nicely in
his excellent article on GUI architectures (http://martinfowler.com/eaaDev/
uiArchs.html):


Take Model-View-Controller as an example. It's often referred to as a pattern, but
I don't find it terribly useful to think of it as a pattern because it contains quite a
few different ideas. Different people reading about MVC in different places take
different ideas from it and describe these as 'MVC'. If this doesn't cause enough
confusion you then get the effect of misunderstandings of MVC that develop
through a system of Chinese whispers.
Free download pdf