Beginning AngularJS

(WallPaper) #1

CHApTer 6 ■ WorkIng WITH ForMS



First name is: {{person.firstName}}

Street name is: {{person.address.street}}




Listing 6-4 and Listing 6-5 show the general principles of binding in action. Pay special attention to the fact that
we bound to a model property with a nested object (the person object’s address property, which is itself an object).
Both text inputs properly reflect this hierarchy, as shown in bold in the code listing.
More formally, what I have been discussing in this section is known as two-way binding. This distinction is made
because AngularJS also supports one-way binding. You have already used one-way binding, and it is used in Listing
6-5. Here is the portion of code in which the one-way binding appears:


First name is: {{person.firstName}}

Street name is: {{person.address.street}}


We have already seen this type of binding, though, at the time, we didn’t actually use the term one-way binding.
What exactly do I mean by one-way binding? An easy way to understand this is by considering that a user cannot
change a value that is output as plain text content. This is in stark contrast to values that are output to text inputs and
other editable form elements. AngularJS has less work to do with the plain text output, as it does not have to manage
the relationship in both directions. Consequently, this is called a one-way binding. AngularJS will not waste resources
monitoring static content for changes.
In fact, as an alternative to using the double curly brace syntax, you can instead use the ngBind directive. The
preceding code snippet, rewritten with ngBind, would look like this:


First name is:

Street name is:


The double-curly-brace approach is more naturally readable, and it requires less typing than the ngBind
approach. However, ngBind can be useful, as it behaves like the ngCloak directive, discussed previously in the last
chapter, in that content is only visible once AngularJS has loaded.
Here’s a good thing to know about how AngularJS treats bindings in the absence of an associated model property:
if you refer to a model property in an ngModel directive and it doesn’t actually exist, AngularJS will create it for you.
Review Listing 6-6 and Listing 6-7, and then we will have a quick discussion about what this reveals concerning the
binding process.


Listing 6-6. Implict Model Binding—HTML Code










Free download pdf