Mastering Web Application

(Rick Simeone) #1

Angular Zen


In reality, AngularJS has even more intimate connections to HTML and the DOM as
it depends on a browser to parse the template's text (as a browser would do with any
other HTML document). After a browser is done transforming the markup's text to
the DOM tree, AngularJS kicks in and traverses the parsed DOM structure. Each time
it encounters a directive, AngularJS executes its logic to turn directives into dynamic
parts of the screen.


Since AngularJS depends on a browser to parse templates, we need to
ensure that the markup represents valid HTML. Pay special attention to
close the HTML tags properly (failing to do so won't produce any error
messages, but the view won't be rendered correctly). AngularJS works
using the live, valid DOM tree!

AngularJS makes it possible to enrich HTML's vocabulary (we can add new attributes
or HTML elements and teach a browser how to interpret them). It is almost similar
to creating a new domain-specific language (DSL) on top of HTML and instructing
a browser on how to make sense of the new instructions. You can often hear that
AngularJS "teaches browsers new tricks".


Declarative template view – the imperative controller logic


There are many handy directives shipped with AngularJS, and we are going to
cover most of the existing ones in the following chapters. What is probably more
important, however, is not the syntax and functionality of individual directives but
rather the underlying AngularJS philosophy of building UIs.


AngularJS promotes a declarative approach to UI construction. What it means in
practice is that templates are focused on describing a desired effect rather than on
ways of achieving it. It all might sound a bit confusing, so an example might come
in handy here.


Let's imagine that we were asked to create a form where a user can type in a short
message, and then send it by clicking on a button. There are some additional
user-experience (UX) requirements such as message size should be limited to 100
characters, and the Send button should be disabled if this limit is exceeded. A user
should know how many characters are left as they type. If the number of remaining
characters is less than ten, the displayed number should change the display style
to warn users. It should be possible to clear text of a provided message as well. A
finished form looks similar to the following screenshot:

Free download pdf