Beginning AngularJS

(WallPaper) #1
Chapter 2 ■ the BasiCs of angularJs

■ Tip if an ngShow expression evaluates to false, then a Css class named .ng-hide is dynamically added to the


element, causing it to become hidden. so, the element still exists in the DoM, but it is not displayed.


The ngShow directive is very handy. You will use it often for hiding or showing regions of your user interface,
based on user input or other conditions.
Another common directive is the ngClick directive. Just like ngShow, ngClick expects an expression, but unlike
ngShow, this expression is only evaluated when the element it is declared upon is clicked.
Listing 2-5 shows ngClick in action. Load it up in your browser and press the Increment button a few times.


Listing 2-5. Demonstrating ngClick


<!doctype html>




Listing 2-5




count: {{count}}


As you might have guessed, clicking the Increment button causes the value of count to increment. Each time the
button is clicked, ngClick evaluates the expression. As the count variable is used in an expression binding, we can see
its value updated in real time.
Here we have also used the ngInit directive. You typically won’t use ngInit very much, if at all, for reasons that
will make more sense when I discuss the MVC (Model View Controller) approach predominantly used in AngularJS
applications. However, here we use it to initialize the count variable to 0. You could just as easily have set this value to,
say, 10, in order to increment from a starting value of 10 instead of 0.


What Are Expressions?

You’ve seen a few expressions already, but what exactly are they? Essentially, they are JavaScript expressions, just like
the ones you already know and love. However, there are a few important differences.


•    In AngularJS, expressions are not evaluated against the global window object; instead, they are
evaluated against a scope object.

•    You don’t get the usual ReferenceError or TypeError when trying to evaluate undefined
properties. AngularJS expressions are forgiving in that regard.

•    You cannot use conditionals, loops, or exceptions. This is a good thing; you don’t want
complex logic inside expressions. (In Chapter 3, I will discuss where you do want them.)

•    You can use AngularJS filters to format data before displaying it. (I cover Filters in Chapter 4.)

To get a sense of how expressions work and what you can do with them, take a look at Listing 2-6.
Free download pdf