Mastering Web Application

(Rick Simeone) #1

Angular Zen


We can see a recurring pattern here. To manipulate UI, we only need to touch
a small part of a template and describe a desired outcome (display number of
remaining characters, disable a button, and so on) in terms of the model's state
(size of a message in this case). The interesting part here is that we don't need to
keep any references to DOM elements in the JavaScript code and we are not
obliged to manipulate DOM elements explicitly. Instead we can simply focus on
model mutations and let AngularJS do the heavy lifting. All we need to do is to
provide some hints in the form of directives.


Coming back to our example, we still need to make sure that the number of remaining
characters changes style when there are only a few characters left. This is a good
occasion to see one more example of the declarative UI in action, as given in the
following code:


<span ng-class="{'text-warning' : shouldWarn()}">
Remaining: {{remaining()}}
</span>

where the shouldWarn() method is implemented as follows:


$scope.shouldWarn = function () {
return $scope.remaining() < WARN_THRESHOLD;
};

The CSS class change is driven by the model mutation, but there is no explicit DOM
manipulation logic anywhere in the JavaScript code! UI gets repainted based on a
declaratively expressed "wish". What we are saying using the ng-class directive
is this: "the text-warning CSS class should be added to the element, every
time a user should be warned about exceeded character limit". This is different from
saying that "when a new character is entered and the number of characters exceeds
the limit, I want to find a element and change the text-warning CSS class
of this element".


What we are discussing here might sound like a subtle difference, but in fact
declarative and imperative approaches are quite opposite. The imperative style of
programming focuses on describing individual steps leading to a desired outcome.
With the declarative approach, focus is shifted to a desired result. The individual little
steps taken to reach to this result are taken care of by a supporting framework. It is like
saying "Dear AngularJS, here is how I want my UI to look when the model ends up in
a certain state. Now please go and figure out when and how to repaint the UI".

Free download pdf