Angular JS - Freshers

1 ChApter 1 ■ JAvASCrIpt You Need to KNow 2 In this case, the file is called myScript.js, and it resides in a directory named scripts. You can also write your script directly in the HTML file itself. Listing 1-2 demonstrates this technique. Listing 1-2. Using an Inline Script JavaScript Primer Most of the time, it is better to use the first approach and reference a separate file containing your scripts. This way, you can reuse the same scripts in multiple files. The second method, usually referred to as an inline script, is most often used when reuse isn't a requirement, or simply for convenience. Assuming that the file script.js contains the exact same code as the inline script, the browser output would be as follows: Hello For the most part, I will include complete code listings in this chapter, so that you can load them into your browser and experiment. You will learn a lot more by tinkering with code and viewing its output than by relying solely on this drive-by introduction. Statements A JavaScript application is essentially a collection of expressions and statements. Without the aid of other constructs, such as branching and looping statements, which I will discuss shortly, these are executed by the browser, one after the other. Each usually exists on its own line and, optionally, ends with a semicolon (see Listing 1-3). Listing 1-3. Statement Execution JavaScript Primer ChApter 1 ■ JAvASCrIpt You Need to KNow The preceding listing simply logs output to the console and produces the results shown in the output below. If you are unfamiliar with the location of the browser's JavaScript console, you can access it on Chrome, using Tools ➤ JavaScript Console or, if you use Internet Explorer, by pressing F12 to bring up the Developer Tools and then clicking the console icon. Of course, you can use your favorite search engine to find out where the JavaScript console is hiding in your preferred browser. I will be using the handy console.log() approach quite extensively in this chapter, to display the program output. I hope the output shown below is as you would expect it to appear. Although I use two separate script tags here, the output would have been the same even if I had put all of the statements into the first script tag in the exact same order. The browser doesn't really care; it just deals with the scripts as it finds them. I am a statement I am also a statement Here is another statement Here is the last statement You may have picked up on my comment earlier about semicolons being optional. This fact is often a source of confusion. The easiest way to avoid any confusion or code mistakes is simply to use semicolons as though they are required. Don't give yourself the option of omitting them. Nonetheless, here is the backstory. Take a look at Listing 1-4. Neither of the two statements terminates in a semicolon. This is perfectly legitimate from a syntactic perspective. As an analogy, consider reading a sentence in plain English. Even if the writer omits the period at the end of a sentence, you can still infer that a sentence ended, because a new paragraph immediately follows. Listing 1-4. No Semicolons—All Good ... ... Listing 1-5 is a totally different story. Here we have two statements on the same line. This is not legitimate JavaScript, and problems will occur when you run it. More specifically, you will get a SyntaxError: Unexpected identifier error message in most web browsers. Essentially, it is not clear to the JavaScript runtime where one statement ends and another begins. Back to our analogy: it may well be clear when one paragraph begins and another starts, but the same is not true of a sequence of sentences. Listing 1-5. Both Statements on the Same Line—NOT Good 3 ChApter 1 ■ JAvASCrIpt You Need to KNow 4 Listing 1-6 shows how you can restore order and overcome the problem in Listing 1-5. As both statements are on the same line, a semicolon makes it clear where one starts and the other ends. Listing 1-6. Both Statements on the Same Line—All Good As I said, the best way to handle this is to just sidestep it altogether. Use semicolons as a matter of habit and best practice. It isn't always obvious what a statement or group of statements is supposed to do. With that in mind, it is a good practice to add meaningful comments to your code. JavaScript gives you two ways to do just that: single-line comments and multiline comments. Take a look at Listing 1-7. Listing 1-7. Using Comments JavaScript Primer Listing 1-7 is functionally identical to Listing 1-3, but this version uses comments within each script block. The first uses single-line comments, which are useful for short comments that need not span multiple lines. The second uses the multiline approach. Ideally, you should make sure that your comments say something useful about the purpose and context of your code, something that will help you or others understand why it is there. Functions A function is a block of JavaScript code that is defined once but may be executed, or invoked, any number of times. Functions are easy to create: just type the keyword function, choose a name for your function, and put the function code between a pair of curly braces. See Listing 1-8 for an example of a simple JavaScript function. ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-8. A Simple Function JavaScript Primer Here we define a function called mySimpleFunction. We could have named this function mysimplefunction (all lowercase) or even mySIMPLefunCTion (a mixture of upper- and lowercase letters), but best practices dictate that we use an uppercase character at the beginning of each new word (an approach known as camel casing). This makes it much more readable. With the function now in place, we want to make use of it. Using a function is as simple as typing the function name, followed by parentheses, a process known as invoking, or calling, the function. Here we invoke mySimpleFunction two times. It isn't a terribly useful function, but it does illustrate the idea that we only need to set up a function once and then reuse it as often as we like. Here is the output: Hello Hello Parameters and Return Values Let's look at a function that uses parameters and can return a value. We will name it tripler, because it can triple any number with which it is provided. Our tripler function will define a single parameter, a number, and return a value equal to this number multiplied by three (see Listing 1-9). 5 ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-9. A Function with Arguments and a Return Value JavaScript Primer Listing 1-9 shows the tripler function in action. First, we define the function. Still keeping things simple, within the function body (the code between the opening and closing curly braces), we immediately return the result of the computed value back to the caller. In this case, there are two callers: one that passes in a value of 150 and another that passes in a value of 300. The return statement is crucial here. It takes care of exiting the function and passing the computed value back to the caller. Equally important is the numberToTriple parameter, as it contains the value that we are interested in tripling. Again, we use the console to show the output. Sure enough, we get the results of calling our function two times, each time with a different argument passed in and a different result returned. 450 900 ■ Tip I just used the term argument with regard to the value passed into our function. You may be wondering why I didn't stick with the term parameter? well, I probably could have gotten away with doing that, but in reality, they are subtly different things. parameters are things defined by functions as variables, while arguments are the values that get passed in to be assigned to these variables. Types and Variables Variables are the containers that hold the data with which your application works. Essentially, they are named areas of computer memory in which you can store and retrieve values with which you are working. Listing 1-10 shows you how to declare a variable. 6 ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-10. Declaring Multiple Variables at Once JavaScript Primer In the preceding listing, we use the var keyword to declare a new variable and then immediately assign it a value of "red". The output below is then, perhaps, unsurprising. The color is red Listing 1-11 provides another example. This time we declare three variables at once and then assign values to each of them afterward. Listing 1-11. Declaring Multiple Variables at Once JavaScript Primer 7 ChApter 1 ■ JAvASCrIpt You Need to KNow 8 It is common to see multiple variables declared all on the one line, as I have done in Listing 1-11, but you will also see this done with each variable on its own line, as the following code snippet shows: // declare some variables var color, size, shape; I prefer the first approach, but this is generally just a matter of taste. Listing 1-11 produces the output following. Your widget is the color blue and its size is large. It is circular in shape. You will notice that each value that we have used so far has been a string value, that is, a series of characters. This is just one of the types that JavaScript supports. Now let's look at the others. Primitive Types JavaScript supports a number of primitive types. These types are known as primitive types, as they are the fundamental built-in types that are readily available. Objects, which I discuss in the next section, are generally composed of these primitive types. Booleans A Boolean value is intended to represent just two possible states: true and false. Here is an example: var isLoggedIn = true; var isMember = false; Note that, in both cases, we do not put quotation marks around the values, that is, true and false are not the same as "true" and "false". The latter are string types, not Boolean types. Interestingly, if you do happen to assign the string "false" to a variable, in Boolean terms, that variable's value will be true. Consider the following examples: isMember = "false"; isMember = 1; isMember = "Hello"; Each of these variables has an inherent Boolean value, that is, a quality that leads us to categorize them as truthy. That is to say, each of these values represent true. Conversely, each of the following is falsy. isMember = ""; isMember = 0; isMember = -0; ChApter 1 ■ JAvASCrIpt You Need to KNow Strings A string stores a series of characters, such as "Hello JavaScript." You have two choices when creating strings: you can use single quotation marks or double quotation marks. Both of the variables below are string types. var firstName = "Jane"; // enclosed by double quotation marks var lastName = 'Doe'; // enclosed by single quotation marks It doesn't really matter which variation you use, but consistency is good practice. One nice thing about this flexibility is that you can use one within the other. That is, you can use single quotation marks within a string created using double quotation marks, as I do in the following example: // a single quotation mark inside a double quoted string var opinion = "It's alright"; This works both ways, as the following example demonstrates: // double quotation marks inside a single quoted string var sentence = 'Billy said, "How are you today?", and smiled.'; You can also use the handy backslash to achieve the same thing, regardless of which way you create your strings. // using the backslash to escape single and double quotes var sentence = "Billy said, \"How are you today?\", and smiled."; var opinion = 'It\'s alright'; In case it is unclear why we have to handle strings in this way, consider the issue with the string following: var bigProblem = "Billy said, "How are you today?", and smiled."; console.log(bigProblem); This produces the very unpleasant output that follows. As far as JavaScript is concerned, you declared a variable containing the string "Billy said," and then proceeded to type invalid JavaScript code! Uncaught SyntaxError: Unexpected identifier What you should not do is to use single and double quotation marks interchangeably, as I do in the following example: // This is a bad idea! var badIdea = "This will not end well'; Here, I start the string with double quotation marks and end it with single quotation marks—a very bad idea indeed, because this will cause a syntax error. 9 ChApter 1 ■ JAvASCrIpt You Need to KNow Numbers The number type is used to represent numbers in JavaScript, both integers and floating-point numbers. JavaScript will look at the value and treat it accordingly. Listing 1-12 uses a simple script to demonstrate this point. Listing 1-12. Numbers in JavaScript JavaScript Primer Looking at the output below, you can see that JavaScript is mostly doing just what you would expect; however, you will see something that may appear unusual on the last line of output. 4 46 50.6 2525 If you look at Listing 1-12 again, you will see that the variable val8 was actually declared as a string. JavaScript inferred what you intended, and it coerced val7 into type string also. Consequently, you end up with two strings concatenated together (which is how the + operator acts when used on strings). I will talk a little more about JavaScript type conversion shortly. 10 ChApter 1 ■ JAvASCrIpt You Need to KNow Undefined and Null JavaScript has two subtly different types to represent the idea of missing values: undefined and null. var myName; console.log(myName); Here we have a variable called myName to which we have assigned no value. When we print the value of this variable to the console, we get the following result: undefined JavaScript uses undefined to represent a variable that has been declared but has not yet been assigned a value. This is subtly different from the following situation: var myName = null; console.log(myName) In this case, I specifically assigned the value of null. Consequently, the output is as follows: null From these examples, it is clear that undefined and null are two distinct types: undefined is a type (undefined), while null is an object. The concept of null and undefined can be rather tricky in JavaScript, but as a general rule of thumb, you should favor using null whenever you have to declare a variable to which you are not ready to assign a value. JavaScript Operators JavaScript supports all of the standard operators that you would expect to find in a programming language. Table 1-1 lists some of the more commonly used operators. Table 1-1. Commonly Used JavaScript Operators Operator Description ++, -- Pre- or post-increment and decrement +, -, *, /, % Addition, subtraction, multiplication, division, remainder <, <=, >, >= Less than, less than or equal to, more than, more than or equal to ==, != Equality and inequality tests ===, !== Identity and nonidentity tests &&, || Logical AND and OR (|| is used to coalesce null values) = Assignment + String concatenation 11 ChApter 1 ■ JAvASCrIpt You Need to KNow 12 Some of these operators may make intuitive sense, others perhaps not. Let's write a simple program to look at how they behave. There are a couple of cases in which we will look a bit closer at some of these operators, so I will omit them in Listing 1-13 and deal with them shortly afterward. Listing 1-13. Common Operators in Action JavaScript Primer Listing 1-13 shows the output of some basic operations. I've put the output in comments next to each line of code, to make it easier to reconcile. You can use Table 1-1 to clarify your understanding of how each produces its respective output. ChApter 1 ■ JAvASCrIpt You Need to KNow Equality vs. Identity I mentioned previously that I'd like to cover some of these operators as special cases. The identity (===) and equality (==) operators are one such special case. These operators look similar, and they can even appear to behave similarly, but, in fact, they are significantly different. When performing comparisons, the equality operator (==) will attempt to make the data types the same before proceeding. On the other hand, the identity operator (===) requires both data types to be the same, as a prerequisite. This is one of those concepts best conveyed through code, as shown in Listing 1-14. Listing 1-14. Converting Types and Then Comparing JavaScript Primer I'm not sure what you expect to see in the output that follows, given that we are comparing the number 3 to the string value "3". You may or may not be surprised, but these values are considered to be the same. ValueOne and ValueTwo are the same The reason why the == operator reasons that "3" and 3 are the same is because it actually coverts the operands (the values either side of the == operator) to the same type before it does the comparison. However, if we change the operator to an identity operator, as shown here, we see quite different output: if (valueOne === valueTwo) ValueOne and ValueTwo are NOT the same Since we used the === operator on this occasion, and because this operator does not do any type conversion, we see that the string value "3" and the number 3 are not the same after all. When in doubt, a relatively safe choice is simply to use the identity operator (===) as a matter of habit. Of course, the safest choice is to familiarize yourself with the differences, so that you know what is actually happening under the hood. 13 ChApter 1 ■ JAvASCrIpt You Need to KNow 14 JavaScript is very flexible with types, and it allows you significant freedoms, but the tradeoff is that what is going on behind the scenes is not always obvious. For example, you have already seen that the + operator performs double duty: it can do addition and it can also do string concatenation. With that in mind, examine the following code snippet. Can you predict its output? // Will this produce the number 2 or the string "11"? console.log("1" + 1); The output is: 11 From this, we can deduce that JavaScript must have converted the number value to a string value and performed a concatenation operation, as opposed to an addition operation. At times, as you might imagine, we want some control over types. Fortunately, JavaScript comes with the right tools. Table 1-2 shows just a few of the tools you have at your disposal. Table 1-2. A Few Built-in Type-Related Utilities Function / Operator Description typeof Allows you to ask the data type of its operand. It can provide the following values: "number" "string" "boolean" "object" "undefined" null parseInt The parseInt() function parses a string and returns a number. If it cannot return a number, it will return NaN (Not a Number). toString Converts a value, such as a number, to a string isNaN The isNaN function can tell you if a given value is not a number. For example, isNaN('three') will return true; isNaN(3) will return false. Listing 1-15 shows each of these in action. Listing 1-15. Type Conversion Examples JavaScript Primer ChApter 1 ■ JAvASCrIpt You Need to KNow It's well worth exploring these built-in functions and others like them. JavaScript's dynamic type system is often a good thing, but it does mean that any serious JavaScript programmer has to become accustomed to how types are being managed behind the scenes. Pre- vs. Post-Increment I will finish this section by looking at the last of the special cases: the pre- and post-increment operators (++) and their decrement (--) counterparts. These operators are relatively easy to understand on the surface. Essentially, they are a more compact way of performing operations, such as the following: myNumber = myNumber + 1; myNumber += myNumber; Another way that you can achieve the same result as the preceding two techniques is as follows: myNumber = ++myNumber; 15 ChApter 1 ■ JAvASCrIpt You Need to KNow 16 In all cases, the value of myNumber increments by 1. Take special note here that the preceding increment operator appears before the variable myNumber. In this case, we refer to it as a pre-increment. A post-increment, as you might expect, would look like this: myNumber = myNumber++; This seems straightforward enough, so why am I treating these operators as a special case? Because, potentially, there is a serious mistake that can be made when using them. This is demonstrated in Listing 1-16. Listing 1-16. Pre- vs. Post-Increment Behavior JavaScript Primer Read through Listing 1-15, and see if you can figure out why the output is as shown following. The answer lies in the nature of how or, rather, when these operators perform their work. Pre-increment result is 3 Post-increment result is 2 If you found it odd that the post-increment result was 2 instead of 3, here's why: the post increment operation happens after the assignment operation. Let me clarify this by breaking it down a bit. myNumber = ++myNumber; Reading the preceding code snippet in plain English, you might say this: "Increment the current value of myNumber, and then store it into the variable myNumber." However, if you look at the post-increment variation of this: myNumber = myNumber++; ChApter 1 ■ JAvASCrIpt You Need to KNow you now have to interpret this as "Store the current value of myNumber into myNumber, and then increment the value." In this case, the net result is that the increment happens after the assignment operation, so the myNumber variable never actually receives the updated (incremented) value. The same principle applies to the pre- and post-decrement (--) operators. Working with Objects Objects are often used as containers for data, but they can be home to functions too. They are a particularly versatile aspect of the JavaScript language, and it is very important to get a decent handle on this concept. Creating Objects Let's start our brief look at objects by seeing how they are created. Listing 1-17 demonstrates the usual way to create an object. Listing 1-17. Creating Objects JavaScript Primer 17 ChApter 1 ■ JAvASCrIpt You Need to KNow 18 Listing 1-17 shows a few different ways of creating objects. I tend not to use or come across the new Object() technique very much (commented with Example 3 in the listing), and I think you will see the other two approaches used a lot more. Examples 1, 2, and 3 all do the same thing: they create an object, add a couple of properties to it, and assign some values to those properties. Each example logs to the console to produce the following output: Andrew Andrew Andrew ■ Note You can think of properties as variables defined on objects. however, in the world of object-oriented programming, which I don't cover in this book, there are far better definitions. Reading and Modifying an Object's Properties Changing the values of properties can be done in a couple of ways. Listing 1-18 demonstrates accessing and changing object values. Listing 1-18. Accessing and Changing Object Values JavaScript Primer As the following output demonstrates, we start off by setting a value of Andrew on the firstName property; shortly thereafter, we change that value to Monica. On both occasions, we use dot syntax, that is, the object name, followed by a dot and then the property name. Shortly afterward, we change it yet again, but this time, we use associative array syntax. This syntax requires us to use the object name and then to specify the property name within brackets. ChApter 1 ■ JAvASCrIpt You Need to KNow Andrew Monica Catie Which approach you use can often be a matter of preference, but associative array syntax has some nifty benefits. For example, you can use a variable name inside the brackets, which makes for some very handy dynamic behavior. Listing 1-19 provides a quick example of this. Listing 1-19. Associative Array JavaScript Primer The important part of Listing 1-18 is where we update the firstName property using the previously declared propertyName variable. Using dot syntax, you cannot do this. The output is as follows: Catie Christopher ■ Note Be careful when using associative array syntax. If you make a typo and write, say, ["firstNme"] instead of ["firstName"], you will actually create on the object a new property called firstNme. 19 ChApter 1 ■ JAvASCrIpt You Need to KNow Adding Methods to Objects We looked at functions earlier, and now we are going to look at methods. Here's the good news: methods and functions are so similar, you are already most of the way there. Let's look at the example shown in Listing 1-20. Listing 1-20. An Object with a Method JavaScript Primer If you look through Listing 1-20, you will see that it isn't really anything special, until you get to the myInfo property. This property has a value just like any other property, but it just so happens to be a function. The last line shows it being called through the object reference. A function attached to an object in this manner is known as a method. Why is that? The short and simple answer is that, in reality, they are subtly different things, both in how JavaScript treats them and how you, as a developer, are supposed to use them. Did you notice that inside the myInfo method we refer to name as this.name? Using the special this keyword, you get access to other properties of the same object. Essentially, this is a reference to the current object. (Some of you may be familiar with other languages in which something like this exists under the guise of Me or self.) Here is the output: My name is Andrew. My age is 21. I want to make a minor change to the preceding listing. Here is a snippet of the affected area, the myInfo method: myInfo: function () { console.log("My name is " + firstName + ". "); console.log("My age is " + age + "."); } 20 ChApter 1 ■ JAvASCrIpt You Need to KNow Everything is identical, except for the fact that I removed the this keyword from firstName and age. This is an example of what not to do. As the following output shows, my browser didn't like it one bit. Uncaught ReferenceError: firstName is not defined The moral of the story is this (no pun intended): make sure that you access the current object's properties via the this keyword, if you want to avoid unpredictable results. I cannot delve much into object-oriented programming techniques here, as this is a huge topic that would fill many books in its own right. However, although I didn't touch upon it much here, it is worth knowing that JavaScript does support this paradigm quite well, should you wish to explore it further. Enumerating Properties You can use a for in loop to enumerate an object's properties. This is an easy way to interrogate any object, and it has many other uses as well. Listing 1-21 provides an example of a for in loop. Listing 1-21. The for in Loop JavaScript Primer Listing 1-21 uses a for in loop to print each property of myObject to the console. It can be extremely handy at times, though this example isn't exactly awe-inspiring. All we do here is use the variable prop, which changes with each pass through the loop, to print the property's value to the console. 21 ChApter 1 ■ JAvASCrIpt You Need to KNow Andrew Grant 21 Remember the use of the associative array syntax that we discussed earlier? myObject[prop] is a good example of where this technique is needed. Control Flow Generally speaking, JavaScript is read by the browser line by line, unless you tell it otherwise, using, for example, a loop or branch statement. Looping is the ability to repeat the execution of a block of code a number of times; whereas branching is the ability to jump to one block of code or potentially some other block of code. Loops Let's start off with loops. Arguably the most common loop structure in JavaScript is the for loop. The for loop can seem complicated at first, but it's not difficult to use, once you understand what it is composed of. There are four key parts to a for loop: 1. Counter variable. This is something that is created and usually used only in the for loop. Its main task is to keep count of how many times the loop has been entered. 2. Conditional logic. This is where the decision is made on whether or not the for loop should continue. 3. Counter variable. This is usually incremented, or otherwise altered, after every loop. 4. Code block. This is the actual block of code that is executed at each pass through the loop. With these explanations in mind, let's examine Listing 1-22, which shows the for loop in action. I hope you will be able to read through this and relate each part back to the preceding points. Listing 1-22. The for Loop in Action JavaScript Primer The first thing we do is to print Looping started to the console. Then we enter the for loop. We enter the for loop because of the conditional check, the bit that reads i < 5. Well, i (which is the counter) starts off at 0, so i < 5 evaluates to true. Only when i < 5 evaluates to false will the loop end and continue on to the next line of code, in this case, the code that prints Looping finished to the console. So, why would the variable i ever change its original value of 0? This is because each time the loop executes, it also carries out the i++ logic. So, the counter goes up at each pass and eventually the loop ends. The results follow. We will see the for loop in action again when I cover JavaScript arrays shortly. Looping started The current value of i is 0. We will loop again because 0 is less than 5 The current value of i is 1. We will loop again because 1 is less than 5 The current value of i is 2. We will loop again because 2 is less than 5 The current value of i is 3. We will loop again because 3 is less than 5 The current value of i is 4. We will loop again because 4 is less than 5 Looping finished The while loop is a somewhat simpler version of the for loop. It doesn't require as much setup, but it isn't quite as powerful (at least not without extra work). The basic structure of a while loop looks like this: while( some value is true){ execture this block of code } The preceding isn't real code, of course, but Listing 1-23 provides a basic demo of the while loop. Listing 1-23. The while Loop in Action JavaScript Primer 23 ChApter 1 ■ JAvASCrIpt You Need to KNow 24 You might consider the while loop to be a less structured version of the for loop. Indeed, you can happily program in JavaScript, forever ignoring the while loop by exclusively using the for loop. However, you will come across many situations in which using a while loop can be very convenient and much more concise. Conditional Statements Conditional statements allow you to implement "fork in the road" logic. That is, JavaScript can execute a statement, or statements, if a specified condition is true. You can also execute a statement, or statements, if this condition is false. Is this user logged in? Yes? Let him/her see this data. No? Then send him/her to the login page. Listing 1-24 demonstrates how to write this kind of logic in JavaScript. Listing 1-24. JavaScripts if/else in Action JavaScript Primer By assigning false to the userIsLoggedIn variable, we are setting up a pretend user that we can consider to be not logged in, just so we have something with which to work. Next is the if(userIsLoggedIn) portion of the code. The if statement expects whatever expression or variable is placed between these parentheses to evaluate to either true or false. It will only execute the code in the associated code block if it finds a value of true. Should it find a value of false, it will execute the block of code within the else statement. I hope the following results will make perfect sense. Sorry - access denied You do not have to provide an else statement if your program doesn't require it. Also, you can nest if and if/ else statements inside of each other. Listing 1-25 demonstrates both of these ideas. ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-25. Nested Conditional Logic JavaScript Primer This listing is similar to Listing 1-23, the difference being that there is no else counterpart to the if statement. In these cases, when the condition evaluates to false, no action is taken at all. Also, we use a nested if/else statement. So, if the user is logged in, we ask yet another question: is this user a VIP member? As userIsVIP evaluates to true, we give this member a much higher discount. Welcome back - showing you to some very private data You are entitled to a 25% discount! Working with Arrays JavaScript arrays are used to store multiple values in a single variable. JavaScript arrays are quite flexible in that you can store variables of different types within them. (Some languages do not allow for this.) Arrays allow you to work, based on the position of contained items, by using a numeric index. Listing 1-26 is a basic example of creating an array and adding values to it. 25 ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-26. Working with Arrays JavaScript Primer Here, we create an array called myArray and populate it with five string values. As arrays in JavaScript are zero- based, we start off at zero and finish up at four, for a total of five items. The results follow: Item at index 0: Andrew Item at index 1: Monica Item at index 2: Catie Item at index 3: Jenna Item at index 4: Christopher It can be somewhat tricky trying to keep the index straight, that is, keeping track of which item is at which position. JavaScript provides the Array.length property, so that you have something with which to work. Listing 1-27 provides an example using the length property. Listing 1-27. Using the Length Property ... var myArray = []; myArray[myArray.length] = "Andrew"; myArray[myArray.length] = "Monica"; myArray[myArray.length] = "Catie"; myArray[myArray.length] = "Jenna"; myArray[myArray.length] = "Christopher"; 26 ChApter 1 ■ JAvASCrIpt You Need to KNow // Display the first item console.log("The first item is: " + myArray[0]); // Dislay the last item console.log("The last item is: " + myArray[myArray.length - 1]); ... Listing 1-27 is similar to Listing 1-26, but instead of hard-coding the index values, we use the length property to calculate the current position. Note the need to cater to the zero-based nature of arrays. Accessing the last item in the array requires us to subtract 1 from the length property. The first item is: Andrew The last item is: Christopher Array Literals The manner in which we have gone about creating arrays so far might be considered the long way. I will show you an alternative way, which is more concise and, arguably, more readable when you are creating an array and populating it with values all in one go round. Instead of doing this: var myArray = []; myArray[0] = "Andrew"; myArray[1] = "Monica"; myArray[2] = "Catie"; myArray[3] = "Jenna"; myArray[4] = "Christopher"; you can achieve the same result doing this: var myArray = ["Andrew","Monica","Catie","Jenna","Christopher"]; This is certainly the style I prefer in most cases. I chose the first approach mainly because it was more demonstrative of the index-based nature of arrays. Enumerating and Modifying Array Values The usual way of enumerating an array is to use a for loop, which I covered in the "Control Flow" section earlier in this chapter. Listing 1-28 shows this approach in action. Listing 1-28. Enumerating an Array var myArray = ["Andrew","Monica","Catie","Jenna","Christopher"]; for(var i = 0; i < myArray.length; i++) { console.log(myArray[i]); } 27 ChApter 1 ■ JAvASCrIpt You Need to KNow 28 The output of Listing 1-28 follows: Andrew Monica Catie Jenna Christopher As you can see, this approach hinges on the use of the Array.length property, looping through from 0 to the very last index in the array. Modifying array values is the same as modifying the values of any other variable, with the exception that you need to know its location within the array. Listing 1-29 shows how we can update the entire array by adding the family surname to each item. Listing 1-29. Modifying Array Values JavaScript Primer The most important part of this listing is myArray[i] = myArray[i] + " Grant";. All we do here is append the family surname to the existing value at position i at each pass through the loop. Notice that I also log the entire array to the console both before and after I modify the array's contents. Passing the array to console.log() is a handy way to dump the contents of the entire array for inspection. The output is as follows: Before: ["Andrew", "Monica", "Catie", "Jenna", "Christopher"] After: ["Andrew Grant", "Monica Grant", "Catie Grant", "Jenna Grant", "Christopher Grant"] ChApter 1 ■ JAvASCrIpt You Need to KNow Callbacks Callbacks can be a bit confusing, both for new programmers and for seasoned professionals alike (at least for those new to the functional programming style upon which callbacks are based). The key to enlightenment, I think, is first to understand that functions are objects that can be passed around just like any other value in JavaScript. Let's step through this slowly. Listing 1-30 provides an example that shows how you can create a variable and then store a function in that variable. Listing 1-30. Storing a Function Reference in a Variable: Part 1 JavaScript Primer Listing 1-30 is quite short, but a particularly important concept is illustrated within it. We start off by declaring a variable called myFunctionReference, in which we store a function or, rather, a reference to a function. You might think that the function looks a little odd; it has no name. That's OK because it is stored in the variable myFunctionReference, so when we want to use this function, we can use the parentheses to call it. Look closely at the last three lines. In two cases, I use the parentheses, but in one case, I do not. In the case in which I do not, the function reference is not called (or invoked). It is the parentheses, also known as the call operator, that cause the function to run. Here are the results: callbacks part 1 callbacks part 1 This idea that functions are themselves values that can be assigned to variables is important. Listing 1-31 is done in a way that may (or may not) seem more intuitive, if you have not used anonymous functions (functions without a name) before. 29 ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-31. Storing a Function Reference in a Variable: Part 2 JavaScript Primer Listing 1-31 defines a function and stores a reference to that function in two separate steps. This time around, the function has a name. We can use both its name and the reference to call it. The following output confirms this. callbacks part 2 callbacks part 2 callbacks part 2 callbacks part 2 callbacks part 2 Keeping in mind the idea of functions as values that can be assigned to variables, we now look at callbacks. Callbacks are just functions that you pass to some other function, so that they can be called at some later point. The reasons you might want to do this may vary, but it is generally due to some circumstance for which you must wait some time before your function has enough context to execute meaningfully, such as with Ajax calls to a web server. ■ Note Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. this makes it possible to update parts of a web page without reloading the whole page. one of the ways AngularJS supports this is through its $http service, which we will see more of in Chapter 7. 30 ChApter 1 ■ JAvASCrIpt You Need to KNow Listing 1-32 is a little contrived, but it shows the general idea of how callbacks work. Listing 1-32. A Simple Callback in Action JavaScript Primer Here we have a variable called actionsToTakeWhenServerHasResponded. This variable is a function reference. On the next line down, we have a function called communicateWithServer. The thing to take note of here is that this function takes an argument, which we have named callback, which it expects to be a function reference. Finally, on the last line, we call the communicateWithServer function and pass it the actionsToTakeWhenServerHasResponded variable. I hope that you can see that inside our communicateWithServer function, our actionsToTakeWhenServerHasResponded function is executed through the callback reference. See the following results: The server just responded! For the most part, this example represents the nature of callbacks. One thing it doesn't do very well is demonstrate time passing as the communicateWithServer does some presumably lengthy task. This is really the point of callbacks—your program can continue to execute as opposed to sitting idle waiting for some lengthy process to finish. Here is a code snippet that shows how this might look in action: console.log('1') $http.post('/ http://someurl.com/someService ', data).success(function () { console.log('2') }); console.log('3') 31 ChApter 1 ■ JAvASCrIpt You Need to KNow 32 The interesting part of this example is the success method. It takes a function as an argument. We didn't bother to store the function in a variable this time. It is created right there in the method call (a very common technique). The $http.post() method has to call a server and wait for a response. At some later point, with all going well, the success method will execute the callback function that we passed to it. This process takes, typically, at least a couple of seconds or so. Have a look at how the output for such a scenario would look. 1 3 2 The key thing to observe here is that 3 comes before 2 in the output. This is because the callback function, which contains the console.log('2') statement, takes place at some point in the future. Thanks to the power of callbacks, your program doesn't have to wait around; it continues executing as normal, happy in the knowledge that there will be "call back" later. JSON JavaScript Object Notation, or JSON, is a lightweight data-interchange format. Essentially, it is way of representing data in a way that is much more compact than XML yet still relatively human and totally machine-readable. If you need to send data from place to place, or even store it somewhere, JSON is often a good choice. Because JSON is JavaScript (well, a subset of JavaScript, to be precise), it is easy to work with. Unlike XML, it is considerably faster over the wire. I won't labor too much on JSON, but I will show you what it looks like. Listing 1-33 shows a sample of JSON data. Listing 1-33. Sample JSON Data { "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } I covered JavaScript objects earlier, so I hope this will look familiar. This is essentially a JavaScript object with a bunch of properties representing contact data for a John Smith. firstName and lastName have simple string values. The address property is itself represented as an object, and the phoneNumbers property is an array. ChApter 1 ■ JAvASCrIpt You Need to KNow The same thing in XML is considerably more verbose, relatively difficult to manipulate in JavaScript, and more memory- and storage-intensive. Listing 1-34 shows the JSON from Listing 1-33 represented as XML. Listing 1-34. The JSON from Listing 1-32 Represented as XML John Smith
21 2nd Street New York NY 10021
212 555-1234 646 555-4567
It's important to keep in mind that JSON is an alternative to XML, not a replacement. XML has its advantages too: it is more self-descriptive and arguably more human-readable than JSON. That being said, when wearing your JavaScript hat, you will very likely come across JSON much more often, as it is heavily used in many common scenarios, such as communicating with back-end servers. Summary This whirlwind tour of JavaScript won't make you an expert, but I hope it has been a useful refresher or a quick introduction. We looked at core language features, such as statements, functions, arrays, and objects. We will be using these features throughout the rest of the book. Where it is helpful to do so, I will include some handy tips and notes that elaborate on these topics and others. This should prove particularly useful for readers who are tackling the JavaScript learning curve somewhat parallel to AngularJS. 33 CHAPTER 2 The Basics of AngularJS JavaScript is an important language for web developers—one that is nearly impossible to ignore. It's a language that was created for the relatively simple purpose of adding basic interactivity to web pages. However, it has risen to mainstream importance, and it is used today to build large and sophisticated web applications. Why We Need Frameworks You may develop some appreciation of why frameworks such as AngularJS exist, by considering that JavaScript was not originally created with today's much more complex requirements in mind. In fact, in many respects, JavaScript was adapted to this purpose because it was there. It was already widely supported in web browsers, and many developers knew how to use it. JavaScript sometimes gets a bad rap; it isn't everyone's favorite language. I personally enjoy using it and find that I can work around the things that I perceive as shortcomings; nevertheless, I totally understand why some developers don't feel the same way as I do, particularly those who have not had the chance to warm up to its strengths. I think it is fair to say that JavaScript has many great features, but it is equally fair to say that it is missing a few features—ones that developers feel are vital. Given its humble beginnings and perceived shortcomings, is JavaScript really ideal for developing modern web applications? It certainly is. As a relatively easy-to-learn language with almost ubiquitous support, it is extremely well suited to the task. Here's a better question: Is JavaScript ideal for developing applications that require modularity, testability, and developer productivity? The short and simple answer to a question such as this is no, not really. At least not "out of the box." The makers of JavaScript simply didn't have these requirements in mind when it was conceived. However, today we have a proliferation of frameworks and libraries designed to help us with such things. The general idea is that we want to be more productive and that we want to write code, often in response to unreasonably tight deadlines, that we can easily maintain and reuse. This is why we need frameworks. Each framework achieves its (sometimes significantly different) objectives in a variety of ways and to varying degrees. For example, the popular jQuery framework addresses direct Document Object Model (DOM) manipulation extremely well, but it doesn't really help out much when it comes to keeping your code structured and organized. To be fair, jQuery is more of a library than a full-fledged framework, so this really relates more to my point about varying objectives and degrees. With regard to front-end web development, AngularJS addresses many, if not all, of the issues developers face when using JavaScript on its own, and it does so in a very elegant and comprehensive way. There often isn't a right or wrong framework, by the way, because much of what constitutes right may depend on the kind of project on which you are working, your current skills and experience, and your personal preferences. That being said, I personally believe that AngularJS is a great all-around framework, which is definitely among the best available. 35 Chapter 2 ■ the BasiCs of angularJs ■ Note angularJs comes bundled with a trimmed-down version of jQuery called jqlite. generally speaking, however, it is better to do things the "angular Way." You will learn a lot more about what that means as the book progresses. What Is a Framework? Before exploring AngularJS in depth, let us consider exactly what AngularJS is. What do we mean by a "framework," and why would we want to use one? Might it be a good idea not to use one? Might it even be a good idea to develop our own instead? The dictionary definition tells us that a framework is "an essential supporting structure." That sums up AngularJS very nicely, although AngularJS is much more than that. AngularJS is a large and helpful community, an ecosystem in which you can find new tools and utilities, an ingenious way of solving common problems, and, for many, a new and refreshing way of thinking about application structure and design. We could, if we wanted to make life harder for ourselves, write our own framework. Realistically, however, for most of us, this just isn't viable. It almost goes without saying that you need the support of some kind of framework, and that this framework almost certainly should be something other than your own undocumented (or less than well understood) ideas and thoughts on how things should be done. A good framework, such as AngularJS, is already well tested and well understood by others. Keep in mind that one day others may inherit your code, be on your team, or otherwise need to benefit from the structure and support a framework provides. The use of frameworks isn't uncommon; many programmers from all walks of life rely on them. Business application developers use frameworks, such as the Microsoft Entity Framework, to ease their pain and speed up development when building database-related applications. For example, Java programmers use the LibGDX framework to help them create games. (We all need a little help.) I hope I have sold you on the need for a framework and, more specifically, the fact that AngularJS is a great choice. Now, I will spend the rest of this book getting you up to speed as quickly as possible, while putting you on a solid footing to go further than I can take you within its pages. AngularJS is not difficult to learn, and, if you are like me, you will enjoy its unique approach and its knack for making the complex seem considerably less so. Downloading and Installing AngularJS Downloading and installing AngularJS is easy, takes very little time, and doesn't require your credit card. It is completely free of charge (under the MIT license). To download AngularJS, head on over to http://angularjs.org and follow these steps: 1. Create a folder on your computer called BeginningAngularJS. Inside this folder, create a subfolder called js to contain your JavaScript files. 2. On the AngularJS home page, click the Download button. You will see a dialog box like the one shown in Figure 2-1. 36 (legacy) for the branch option and Minified for the build option. 4. Click the Download button to start the download process. 5. Once the download has completed, move the downloaded file, angular.min.js, into the js folder that you created earlier (assuming you did not save it there directly). 6. That's it! You just downloaded and installed AngularJS. Throughout this book, I will assume that you have followed the preceding steps when I refer to file system locations and folder names. If you are comfortable with the Content Delivery Network (CDN), and prefer to use it, feel free to do so. Likewise, if your preference is to use the non-minified version of the AngularJS library, go right ahead. This won't affect the output of any of the code listings (assuming that you have things set up correctly otherwise). Note ■ Content Delivery networks are a great place to host Javascript libraries, such as angularJs. they provide speed and performance benefits, and they can be much more bandwidth-friendly. google, Microsoft, Yahoo, and other large web organizations offer CDn services for free. You may have noticed that angularJs provides an option to use the google CDn as an alternative to downloading the script and hosting it yourself (see the url in the field labeled CDn). Browser Support All modern web browsers support AngularJS. This list includes Safari, Chrome, Firefox, Opera, IE9 and later versions, and mobile browsers, including Android, Chrome Mobile, and iOS Safari. Generally speaking, browser support is not an issue; AngularJS is very much here and now. Figure 2-1. The AngularJS download options dialog 3. You want the 1.2.x-minified version, so make sure that you choose 1.2. x Chapter 2 ■ the BasiCs of angularJs 37 Chapter 2 ■ the BasiCs of angularJs ■ Note the ninth and later versions of internet explorer are supported. at the time i write this, support for internet explorer 8 is about to be dropped. Of course, you should always know your target audience and test your applications across as broad a range of devices and platforms as possible. Fortunately, the AngularJS community is large (and growing fast), so it's definitely worth heading in that direction if you have questions. Of particular interest are the case studies that you can use to get a sense of AngularJS in action (see http://builtwith.angularjs.org). Your First AngularJS Application Let's start our journey toward AngularJS enlightenment by creating a very small and simple application, albeit one that demonstrates little more than how to include AngularJS on a web page, and use it to display the traditional Hello World greeting. Save Listing 2-1 into your BeginningAngularJS folder. Listing 2-1. Hello World Listing 2-1

Hello {{'Wor' + 'ld'}}

While this is about as simple as it gets, there is actually quite a lot going on here. It's well worth dissecting this and reviewing how each line works, as there are a few important concepts at play—concepts that are fundamental to the way AngularJS works and, therefore, key to how to think in AngularJS. ■ Caution angularJs isn't quite like other frameworks, and it may require you to think a little differently than you are used to. i initially found that i was writing angularJs code with my jQuery hat on, and this proved extremely counterproductive! i will talk more about this shortly in the section "Declarative vs. procedural programming." In the first line of the program, we have the HTML5 doctype. Though this is not strictly necessary for AngularJS to work, it is the doctype you should be using for today's rich Internet applications. The second line is where it becomes interesting. We have declared an ngApp directive within the opening HTML element. I will expand on this directive (and directives in general) a little bit later in this chapter and then much more in Chapter 5. We use ngApp to let AngularJS know which element is to be considered the root of the application. As we have declared it within the HTML element, we are declaring that the whole document is to be "under the control" of AngularJS. Moving down to the fifth line, you can see that we have included the AngularJS library using the script element. If we didn't include the AngularJS library, we wouldn't see any AngularJS goodness. 38 Now for something very exciting: if you move down to the eighth line, you will see an AngularJS expression, as delimited by the opening and closing double curly braces—{{ and }}. We keep things nice and simple here and concatenate the two string literals 'Wor' and 'ld'. AngularJS expressions are powerful, and you will see many of them in this book. Here we use one in a somewhat contrived way, simply to illustrate how they are put into action. The interpolated value is, of course, the string World. When we place an expression between double curly braces like this, we create an expression binding. In a nutshell, this means that the value of the expression is bound. Anytime it changes, the binding will update too. Bindings and expressions will be second nature to you in no time, as these are at the core of how AngularJS works. You can see the result of this in Figure 2-2. Chapter 2 ■ the BasiCs of angularJs Figure 2-2. The output of our Hello World listing I said it was very exciting, didn't I? Well, perhaps I exaggerated a little bit. Nonetheless, it is an AngularJS application, and it gets you started on your journey. We will do something a little more interesting shortly, but let's summarize the key steps we took in Listing 2-1. • We used the ngApp directive to inform our page that it should consider itself under the control of AngularJS. • We then used a script element to include the AngularJS library. • Just to prove everything was hooked up correctly, we used a simple AngularJS expression binding to do some basic string concatenation. That wasn't difficult at all, but let's tinker with Listing 2-1 a bit, just to get a little bit more insight into how AngularJS ticks. Listing 2-2 is a revised version. Listing 2-2. Tinkering with the Hello World Listing Listing 2-2 39 Chapter 2 ■ the BasiCs of angularJs 40

Hello {{'Wor' + 'ld'}}

Hello {{'Wor' + 'ld'}}

All that we have done here is to move the ngApp directive out of the opening HTML element and place it on the first paragraph element. We also added another paragraph element, which is almost identical to the first. However this one is without an ngApp directive. Save Listing 2-2, and load it up in your browser. Two interesting things happen: 1. The first interesting thing is that the expression binding in the first paragraph worked just as it did before. Even though we relocated the ngApp directive, the expression binding is still nested within its boundaries and, therefore, still under AngularJS control. 2. The second interesting thing is that the second paragraph uses an expression too. However, this expression binding simply renders as is; it is not evaluated at all. AngularJS simply isn't interested in it, because it is not contained within the boundaries of an ngApp directive. In fact, AngularJS has no knowledge of this particular paragraph element or anything contained within it. In this book, I will always declare the ngApp directive on the HTML element. While it is handy to know that you can tell AngularJS to manage only a specific portion of the DOM, I want you to see the effect of it being in the wrong location, or missing altogether. Forgetting to add the ngApp directive is one of the most common mistakes that beginners make. ■ Note it is technically possible, though not terribly common, to use more than one ngApp directive per page. there are a couple of limitations, however. first, they must not be nested within each other. second, you have to write extra code to make angularJs recognize all but the first one. it's a relatively advanced scenario that i will not be covering in this book. This sets us up nicely with some working AngularJS code, but it doesn't really hint much at what makes AngularJS such a powerful framework. Listing 2-3, while still small and simple, starts edging toward this. Listing 2-3. Live Updates Listing 2-3

You entered: {{city}}

Chapter 2 ■ the BasiCs of angularJs Here we have declared the expected ngApp directive and AngularJS script reference with which, it is hoped, you are already comfortable. The two important lines are the two lines contained within the body element. The first declares a standard HTML text input, but with one very important addition—the ngModel directive, which we have assigned the value of city. The second line, via an expression binding, uses this value to reference the text that the end user enters into the text field. Save Listing 2-3 and load it up in your browser. This is where the magic starts to happen. Start typing into the text field and watch as the text in the paragraph below the text field updates in real time. What makes it so magical is the amount of code that it took to achieve this result—not very much code at all, no? It's not really magic, of course. At least not in the Harry Potter sense. However, something very sophisticated is clearly taking place. Already, we can see that AngularJS must be hard at work for us, monitoring the application for data changes, updating the DOM to show these changes to the end user, and other things that we are yet to encounter. Other frameworks require that you tackle some or all of this work yourself. AngularJS wants you to focus on your primary concern—your application, not its plumbing. Another interesting point is that we didn't actually write any JavaScript code! You will find that AngularJS has a strong lean toward a declarative, as opposed to a procedural, coding style. Obviously, you have to write JavaScript at some point or other, but AngularJS encourages you to put this in the right parts of your application. As you might expect, a good portion of this book will look at just what constitutes these "right parts." Declarative vs. Procedural Programming A classic example of a declarative programming language to which many developers can easily relate is SQL. When you write an SQL query against a database such as MySQL, you don't really do the heavy lifting yourself. Instead, you give rather high-level instructions to the database engine via a relatively simple select statement. You don't worry about how the database engine should pull the data together in the most efficient way, and you don't worry about things such as control flow and looping constructs—you just issue a select statement and expect the database to give you back the data that you want. In a sense, you declare what you want, and it does the work for you. Procedural programming, on the other hand, requires a more detailed and lower-level set of instructions. In the extremely procedural C language, for example, you must take great care to reserve memory, detail the specific instructions you want to be executed, and then worry about freeing up memory, making sure your algorithms perform well and are thoroughly tested, and all sorts of other things. Declarative programming is much more convenient than procedural programming, because it is often faster and easier. You generally don't have the same kind of granular control that you do with procedural programming, but you often don't need it. In fact, as you will see, AngularJS won't mind at all if you want to adopt a procedural approach when it suits you. Directives and Expressions Let's have a look at a few more AngularJS directives. Directives are a great example of the declarative programming style that AngularJS encourages you to adopt. They are also at the heart of AngularJS, and they are a crucial part of how you will deliver a great user experience. What Is a Directive? AngularJS uses directives to augment HTML with extra functionality. Essentially, directives are a convenient way to declaratively call JavaScript functions. We will look at directives in much more detail in Chapter 5. For now, though, following is a decent overview of directives. Let's try out the very handy ngShow directive. Check out Listing 2-4. 41 Chapter 2 ■ the BasiCs of angularJs Listing 2-4. A First Look at ngShow Listing 2-4

Paragraph 1, can you see me?

Paragraph 2, can you see me?

Paragraph 3, can you see me?

Paragraph 4, can you see me?

Listing 2-4 shows four paragraph elements, each has been "augmented" by an AngularJS directive that goes by the name of ngShow. ■ Note the astute reader may have noticed that i have used the term ngShow in my writing and the subtly different term ng-show in my code. Which is correct? angularJs typically refers to directives in documentation by their case-sensitive, CamelCase name (for example, ngShow) but refers to directives in the DoM by using lowercase, dash-delimited attributes (for example, ng-show). What does ngShow do? Much of the answer is in the name. The ngShow directive will show, or hide, the element on which it is declared, based on the expression provided to it. Load up Listing 2-4 in your browser, and you will see that only the first and third paragraphs appear (as confirmed in Figure 2-3). They only appear because, in both cases, their respective expressions evaluate to the Boolean value of true. The second and fourth paragraphs, however, do not appear because their respective ngShow expressions evaluate to the Boolean value of false. 42 Figure 2-3. ngShow in action 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 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. 43 Chapter 2 ■ the BasiCs of angularJs Listing 2-6. A Quick Look at AngularJS Expressions Listing 2-5

Expression Samples

6 + 4 = {{6 + 4}}

{{"Beginning AngularJS".toUpperCase()}}

{{"ABCDEFG".indexOf('D')}}

{{1==1 ? "Red" : "Blue"}}

There is nothing complex going on here. It's all run-of-the-mill JavaScript code but now using AngularJS expressions. Figure 2-4 shows the results. 44 Figure 2-4. AngularJS expressions in action There are definitely a few more things to know about expressions, and we will get to them as you learn more about how we should be structuring and organizing our code. This is exactly what I will discuss in the next chapter. Chapter 2 ■ the BasiCs of angularJs Summary This chapter explored the concept of frameworks and why you would want to use one. At this stage, I hope that you are feeling quite confident that AngularJS is the right one for you and that you are eager to learn much more in the coming chapters. You have downloaded and installed AngularJS, gained a sense of its "declarative-powered" directives, and witnessed its very tidy use of expressions. You are in great shape already, and it's nearly time to get into the finer details. Before we do that, however, I will take a slight detour in Chapter 3 and discuss some big picture topics, including how to organize and structure AngularJS applications. 45 CHAPTER 3 Introduction to MVC We have taken a quick look at AngularJS and how to get a simple Angular-based web page up and running, but the reality is that you don't need AngularJS if all you want to do is build a very basic application. One of the major strengths of AngularJS lies in its ability to help you properly organize and structure your applications, and very small applications tend not to benefit much at all from this. Of course, smaller applications should be properly structured too, but such applications are not as likely to require the rigid underpinnings and formal structure of a medium- or large-sized application. The way you would approach pitching a tent is not the same way you would approach building a log cabin. With that in mind, in this chapter, we will look at what it means to organize and structure an application and how the Model View Controller (MVC) pattern can help you to do both. Design Patterns Before we get into MVC, let's talk about design patterns for a moment. After all, MVC is a design pattern, so it would be good to know what design patterns are and why you should care about them. Essentially, a design pattern is a documented solution to a recurring problem that programmers have identified—usually in a particular context. Design patterns won't give you the code you need to solve a given problem, but they will propose a well-thought-out and generally accepted approach that you might want to consider adopting yourself. A good way to think of design patterns is that they are like recipes that have been created by programmers who have spent a lot of time in the trenches. These programmers have found out, often through a combination of talent and old-fashioned trial and error, a lot of really great ways to solve specific kinds of problems. Furthermore, these programmers have decided to share these recipes with everyone else. There isn't really a formal standard that states how design pattern documentation should be written, but we will examine something fairly typical. You will generally find something along the lines of what I have outlined in Table 3-1 on design pattern documentation. 47 Chapter 3 ■ IntroduCtIon to MVC Table 3-1. Typical Design Pattern Documentation Title Description Pattern Name and Classification 48 A name that helps in referring to the pattern, often with a classification stating the type of pattern it is Intent The goal of the pattern and the reason it exists Motivation A scenario consisting of a problem and a context in which this pattern can be used Collaboration A description of how classes and objects used in the pattern interact Sample Code Actual code showing how the pattern can be used in a programming language Sometimes, you will find a lot more information about a design pattern than what I present here, but usually you will find at least this much to help you understand its purpose and its intended uses. ■ Tip there is a school of thought that says that MVC is not a design pattern at all, rather it's an an architectural pattern. there is no right or wrong answer, in my opinion, and the important word here is pattern. After reading through any given design pattern documentation and looking at any associated diagrams (which are usually UML based; see the Tip here), you are typically in a much better position to determine if it is applicable to the particular problem you are trying to solve. Patterns certainly are a tremendously useful resource, but there is one really important thing to understand about them up front: they are not silver bullets. Think of them more like friends that give good advice and not so much like divine intervention when you can't find an answer. ■ Tip the unified Modeling Language (uML) is a general-purpose modeling language used in software development. It provides a standard way to visualize the design of software systems. Let's study a very common and relatively straightforward design pattern called the Singleton pattern. This one is well worth knowing as an AngularJS developer, though I have chosen it mainly because it is more digestible in this introductory book than other, more involved design patterns. I don't want to scare you off quite so early in the book! Read through the sample Singleton pattern documentation in Table 3-2. Chapter 3 ■ IntroduCtIon to MVC Table 3-2. Singleton Design Pattern Documentation Title Description Pattern Name and Classification Singleton: an object creational pattern Intent Ensures that a class has only one instance and provides a global point of access to it Motivation Sometimes it makes sense to control the creation of certain objects. For example, rather than allow an application to create numerous database connection objects, it may make more sense to allow for a single connection object, which an application can access through a gateway object, that provides access to a single instance. Collaboration The Singleton collaborates with external objects. Implementation Creates a class that can create a single instance of itself. This should be the only way an instance can be created. Sample Code Sample code is shown in Listing 3-1. Let's work through a scenario. Assume that we found this design pattern documentation through an online search after recognizing an issue within our application. Far too many objects of the same type were being created. Let's further assume that these objects were quite expensive to create, with each object's initialization causing time-consuming and bandwidth-intensive connections to a remote system. We need to fix this. ■ Note one of the first and most well received books on design patterns is Design Patterns: Elements of Reusable Object-Oriented Software by erich Gamma et al. (addison-Wesley professional, 2015). It's well worth checking this book out, if you want to learn more about design patterns and how to use them. So, we have read through the patterns documentation, and we want to figure out if and how this particular pattern can be of any use. The Motivation section of Table 3-2 has got our attention—it certainly seems to fit the bill. It's definitely worth further study to see if the code sample that came with it can shed any light on how we could put it into practice. Let's look at the sample code in Listing 3-1. Don't worry too much if you don't fully grasp what each and every line is doing, as this listing uses some advanced JavaScript techniques that you may not be familiar with yet. Nonetheless, do pay special attention to the comments. Listing 3-1. A JavaScript Implementation of the Singleton Pattern var Logger = (function() { // private variable to hold the only // instance of Logger that will exist var loggerInstance; // Create the logger instance var createLogger = function() { var _logWarning = function(message) { // some complex work coud go here, but // let's just fake it 49 Chapter 3 ■ IntroduCtIon to MVC 50 return message.toUpperCase(); }; return { logWarning: _logWarning }; }; return { // Here is the crucial part. First we check // to see if an instance already exists. If // it does, we return it. If it does not, we // create it. getInstance: function() { if (!loggerInstance) { loggerInstance = createLogger(); } return loggerInstance; } }; })(); // Notice how we use getInstance() and we // do not use direct object creation with the // new keyword var myLogger = Logger.getInstance(); myLogger.logWarning("Memory use nearing maximum!"); This code sample represents a typical code snippet that you might find accompanying design pattern documentation. It just so happens to be written in JavaScript, but it could just as easily have been written in C#, Java, or any other language. (In fact, that is more likely to be the case.) The essential aspect of Listing 3-1 is that it privately manages a single instance of a logger object. It isn't possible to create a new logger object directly. We have to use the getInstance function to access the already-existing logger object (or, if it didn't exist already, the newly created logger object). This is the essence of the pattern, and it seems to be a good solution for the problem we face in our own scenario: our applications issue of numerous objects of the same type being needlessly created, over and over. Along with a code sample such as this, you are likely to come across a UML diagram showing how objects used in a pattern relate and interact with one another. I will stop short of getting into the nuances of UML, and in the case of the Singleton pattern, by definition, there aren't that many relations and interactions to show. The usefulness of design patterns can be difficult to overstate. In our scenario, we had a serious problem within our application, and the Singleton design pattern turned out to be a good way to solve it. This is a relatively simple example of using design patterns to find solutions about which we can feel confident. Other programmers have used this approach, and it is one that has come about through collaboration, testing, refinement, and lots of real-world use. That has to be a good thing. Chapter 3 ■ IntroduCtIon to MVC Design patterns are indeed a valuable resource, but you still have to put plenty of thought into how (and whether or not) to use any given design pattern in a particular context. As specific as design patterns may seem in their description and usage, they are still generalized solutions that may or may not apply to your needs. That being said, a well-documented design pattern will help you make these decisions. ■ Tip reading up on design patterns is actually a great way to improve your code. You may have solved a problem in a particular way, only to find that there is a design pattern dedicated to avoiding the approach you took! It might not be good for the ego, but it's a great way to learn. With this short introduction to design patterns now complete, we can look at the specific pattern that we will use throughout the rest of this book: the Model View Controller (MVC) pattern. You have to learn what MVC is, so that you can apply it within AngularJS. However, we don't actually have to write our own MVC solution, because AngularJS has what you need baked right into the framework. Model View Controller I hope our quick discussion about design patterns has brought to the front of your mind that there are good ways and not so good ways to design your applications and that there are helpful recipes out there that can help you design better applications. Fortunately, the folks who created AngularJS have already put all of the pieces of the MVC pattern into place for you. As the MVC pattern is an architectural pattern, which is realized through a number of other design patterns, I won't include the rather extensive documentation for it here. Instead, we will focus on the AngularJS implementation of it and consider what it does for us. Let's talk about the three major parts of the MVC pattern: the model, the view, and the controller. We're not really speaking at a code level here; rather, we are talking at a higher level about how to organize and structure your applications. MVC is often considered an architectural pattern, which is essentially a pattern that addresses some aspect of an application's overall organization and structure. We will see how MVC comes together in code form later in this chapter, so don't worry too much if it all seems a little abstract as I am discussing it. ■ Tip architectural patterns are often realized through a number of design patterns. as I said earlier, however, the keyword here is pattern. It really depends on what level you happen to be speaking (and quite possibly to whom you happen to be talking). Model The model represents the underlying, logical structure of data in a software application. It's a common mistake to think of the model as the database behind your application, and it is much better to view the model as the body of code that represents the data. View A view is the body of code that represents the user interface (all of the things that the user can see and to which the user can respond on the screen, such as buttons, dialog boxes, and so on). An application generally has multiple views, and each view often represents some portion of your model. 51 Chapter 3 ■ IntroduCtIon to MVC A Separation of Concerns Great! We have some background on the three core components of MVC and how they relate to one another. Though, at this stage, it may not be entirely clear why we should be using it. Now let's take a look at the underlying purpose of this pattern and what sort of problems it solves. As is clear from the definitions above, the controller is actually keeping the model and the view separated—one has no direct knowledge of the other. This is a fairly common design in software engineering, and the term used to describe it is decoupling. When you organize your applications in this manner, it promotes a principle known as Separation of Concerns. Software that has been built around this principle tends to have distinct parts, each of which looks after a particular concern. MVC is a great way of achieving this Separation of Concerns, and before I end this chapter, we will take a quick first look at how AngularJS helps you build your applications in this manner. I have talked a little bit about MVC and Separation of Concerns, but how do these ideas translate into benefits for programmers and end users? Why should we take the extra time and effort it takes to build our applications in this manner? Why MVC Matters A classic benefit of MVC is that you can, with relative ease, add a new format to your application. That is, you can start off with a standard HTML-based set of views and then later add a new set of views supporting a totally different format, such as Silverlight or a native mobile front end. Trying to achieve something like this when your application has been poorly designed would be a nightmare. Take it from someone who has tried it both with and without an MVC-style architecture—the difference in the effort required is huge! The benefit stated previously exists because, through MVC, we apply the principle of Separation of Concerns. The view is in no way exclusively tied to the model, so it is far easier to treat it as a distinct component that we can swap out for another (or, as is quite common, compliment with another). There are also benefits with regard to the methodologies and processes you (and your team) can use. For example, Test-Driven Development (TDD) is very popular at present, and it leads to applications that are much easier to test and continue to test as the application matures. Without achieving a solid Separation of Concerns, it can become much trickier to set up good tests. 52 Controller You can think of the controller as the intermediary for the view and the model. Examine Figure 3-1. You can see that the lines of communication correspond to this idea. Figure 3-1. The MVC lines of communication Chapter 3 ■ IntroduCtIon to MVC There really are many reasons to use MVC, and most of them are based around the commonsense idea that it leads to a much more organized and well-structured application, one with distinct roles and responsibilities. This might seem great from the point of view of the programmer who has to build and maintain the application—clearly life is going to be much easier for this programmer if code has been carefully crafted and well-structured—but how is this of any benefit to the end user of the application? End users benefit from MVC because it leads to applications that are far less prone to bugs and much easier to maintain. This is, of course, a huge benefit, and perhaps the single most important thing toward which we strive. An end user who is provided with stable software, and who is given future releases and updates that don't break things, is a happy end user! MVC is a tried and tested way to build robust applications. Despite the extra up-front effort, it can save hours and hours of time later on. As I said earlier, don't worry if this all seems a little abstract at this stage, because once you see it in action, it will all click into place. Before you know it, it will feel like second nature to you. MVC the AngularJS Way Let's put the theory into practice—at least just a little bit, as this section will not be much more than a drive-by look at the topics that I will cover in much more detail throughout the rest of this book. AngularJS makes the creation of MVC-style applications relatively straightforward and, in my opinion, quite enjoyable. I will point out at this stage, however, that there are a few more moving parts than you may be used to, and a couple of new concepts that you will need to wrap your head around. Let's kick things off by looking at how the model, view, and controller manifest themselves in actual code, via a very simple code example. I will use a partial code listing to represent each concern, and then I will pull it all together into a complete code listing. This way, we can isolate the important parts first and then look at them working together as a whole. The code shown in Listing 3-1 is what we will use to represent our model. var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant']; The employees variable is simply a hard-coded array of employee names. In the real world, this array would usually be populated from a data store of some kind–an SQL database, for example. We don't need to complicate the listing with data-access code. (I will, however, discuss AngularJS support for accessing data later in the book.) The important thing to understand about this line of code is that the array of employees is what represents our model. It's worth making a clarification here, as there is often confusion around the term model. Is the model all of the objects that represent the entities in our data store, or is it just the one specific piece of information that we use in a view (employees being an example of the latter)? The short and simple answer is that it depends on the context, although it is quite common to refer to the former as the domain model and the latter as the view model. Let's turn our attention to the view. Here is a very simple example of what an AngularJS view looks like. In AngularJS parlance, we would call this a view template. As was discussed earlier, the view is concerned with presentation. More often than not, it represents the presentation of data from our model. Number of Employees: {{ ourEmployees.length}} This is basically just HTML and an AngularJS expression, and I will cover what's happening here in a moment. Right now, however, I want you to notice something interesting about Listing 3-2 and Listing 3-3. Neither has any dependency on the other. This is good, and it is in line with our discussions around the desire to achieve a Separation of Concerns. Though it does raise a very interesting question: How does the model data, that is, the employees array, find its way into the view? Let's investigate this right now. Listing 3-2 is where the really interesting stuff starts to happen, as the AngularJS MVC framework is starting to emerge. The function MyFirstCtrl is the controller. It is a common convention in AngularJS to use Pascal case when naming the controller function (that is, to start with a capital letter and use a capital letter for each new word). 53 Chapter 3 ■ IntroduCtIon to MVC Listing 3-2. MVC in Action function MyFirstCtrl($scope) { // populate the employees variable with some model data var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant']; // Now put this model data into the scope so it can be used in the view $scope.ourEmployees = employees; } Review Listing 3-2. We assign the model data to the ourEmployees property that we set on this $scope object. This is the answer: this is how the model data, the employees array, finds its way into the view. The $scope object was supplied to our controller function by the AngularJS framework, and all that we needed to do was to populate it with the data that we wanted to make available to the view. Glance back at the view in Listing 3-2, and notice that the expression uses a reference to ourEmployees. You can think of this expression {{ourEmployees.length}} as effectively being the same thing as {{$scope.ourEmployees. length}}. Don't actually use a scope reference in this manner within an expression; it won't work, as the use of the current scope object is implicit. Listing 3-3 pulls all of this together into a single MVC example. It's short and simple, but the essence of AngularJS is on display here. Listing 3-3. A Complete MVC Example

Number of Employees: {{ ourEmployees.length}}

54 The output, as shown in Figure 3-2, is simply a count of the number of employees, courtesy of the Array.length property. Perhaps the most important aspect of Listing 3-3 is how we use a scope object, an instance of which, as we discussed, was passed into our controller function by the framework. It really is quite fundamental to how AngularJS does much of its work. We can already see it being used to decouple the model from the view, but it actually does something a little bit more impressive than keep our code clean and modular. It is also a key player in the framework's ability to keep the model and the view in sync with each other. The changes made to the model were immediately reflected in the view; we did not have to do any Document Object Model (DOM) manipulation. Tip ■ If you have been working with jQuery for a while, you might find the lack of doM manipulation a bit peculiar at first. jQuery is all about doM manipulation, and you might have to make an effort to shake off that way of thinking when you are working with angularJS. We are nearly at the end of this chapter, but before moving on, I want to show you one more code sample. Listing 3-4 demonstrates another AngularJS approach toward code organization, to keep things clean and crisp. Listing 3-4. Displaying the Employee Names Figure 3-2. Counting the number of employees (output of Listing 3-3) Chapter 3 ■ IntroduCtIon to MVC 55 Chapter 3 ■ IntroduCtIon to MVC

Number of Employees: {{ ourEmployees.length}}

{{employee}}

This listing isn't terribly different from Listing 3-3—there is just one additional line of code. Instead of displaying only the number of employees who work for us, we now use the ngRepeat directive to display the name of each employee who works for us. The ngRepeat directive will repeat the instance of the element upon which it is declared (a paragraph element in this case) for each item in a collection. As Figure 3-3 shows, this results in a total of four paragraphs: one for each of the employees in the ourEmployees array. Consider this a teaser. ngRepeat is quite powerful, and you will definitely be seeing more of it in coming chapters. Summary I hope this chapter has started you thinking about the structure and organization of your applications. In the not-so- distant past, a less formal approach to JavaScript development seemed to work well enough. Scripts were small and played only a small role in application development, so it just didn't matter to the extent that it does now. I started off with a quick discussion about design patterns—just enough to put them on your radar and to let you know that you are not alone. We then looked at the Model View Controller (MVC) pattern, the pattern predominantly used when building AngularJS applications. A quick look at ngRepeat demonstrated that AngularJS isn't just helping us with the higher-level structural aspects of our applications. The declarative approach taken with directives also helps us to keep our code clear and concise. JavaScript is used to build significant portions of web applications, so it is always important to consider application design and structure. 56 Figure 3-3. Introducing ngDirective CHAPTER 4 Filters and Modules When working with data that has been retrieved from a database, you will spend a lot of time working with raw unformatted data. It's not at all uncommon to come across dates that are formatted unusually, numbers that have far too many digits after the decimal point, and people's names that are in all uppercase letters. Keep in mind that data is not always stored in the best format for our own applications, and its original purpose might have been to service a totally different kind of application. When presenting data to end users, however, we need a way to deal with such things. Angular JS filters are often a very good way to do just that. In this chapter, we will look at AngularJS filters, both the built-in variety and custom filters. We will also look at AngularJS modules, which are important in their own right and are a prerequisite for creating custom filters. Introduction to Filters AngularJS filters format the value of an expression for display to the end user. They don't actually change the underlying data, but they do change how it is displayed in the particular case in which the filter is applied. This is much easier to understand with the help of an example. First, let's start off with some sample data (see Listing 4-1) to which we can apply some filters. Listing 4-1. Raw Sample Data Data like this would typically come back from a request to a web service or a database, but we only want some sample data, so that we can learn about AngularJS filters without the additional distraction of data access code. This fictitious data, captured in a JavaScript object we have named someData in Listing 4-1, represents some customer details. We will use this data as the chapter progresses, starting now with a first look at the AngularJS filter syntax. 57 Chapter 4 ■ Filters and Modules 58 The first filter we will look at will address the issue of the firstName and surname appearing in uppercase. To improve this slightly, we will change it to lowercase. To achieve this, the main thing to know is that you use the | (pipe) character, to invoke a filter. Later in this chapter, we will look at how to improve upon this even further, by leaving the first character in uppercase and converting only the remaining characters to lowercase, a technique known as title casing. Listing 4-2 shows how this is done. The MyFilterDemoCtrl controller's only task here is to make the data available to the view. As you will recall from the last chapter, placing it in the scope does this. Listing 4-2. Angular Filter Example Listing 4-2

First Name: {{data.firstName}}
Surname: {{data.surname}}

First Name: {{data.firstName | lowercase}}
Surname: {{data.surname | lowercase }}

Listing 4-2 shows how easy it is to apply the lowercase filter. We apply it by stating the value we want to filter, followed by the | (pipe) character and then the name of the filter. The most important aspects of the code are shown in bold. As Figure 4-1 shows, the first paragraph displays the plain unfiltered data, and the second paragraph displays the filtered data. Chapter 4 ■ Filters and Modules Figure 4-1. lowercase filter—before and after You won't be very surprised to learn that there is a built-in filter named uppercase, which, unsurprisingly, converts characters to uppercase. AngularJS ships with a set of other handy filters, and we look at these in the next section. However, before we get to them, let's take a step back and consider why we might want to use filters. After all, JavaScript already has what you need to perform these kinds of tasks. For example, we could just as easily have added the code for lowercasing data values directly to the controller, instead of using filters. Listing 4-3 takes this approach, and it produces the very same result as Listing 4-2. Listing 4-3. Achieving Same Result Without Filter Using the approach taken in Listing 4-3, it is true that we bypass the need for filters, but there are a few things to consider before you choose to adopt this approach. As I discussed in the last chapter, one very good reason to use AngularJS is because you want to organize your code better and follow some common software development best practices. 59 Chapter 4 ■ Filters and Modules 60 We have talked about the Separation of Concerns principle, so let us take a moment to consider whether or not formatting tasks, such as changing the case of the text we present to our end users, logically belongs in a controller. Doesn't this seem like a task for which the view should be responsible? In one sense, formatting data for presentation is indeed a view-related concern. However, you could also argue that a controller should bear some responsibility for making sure that data is ready for use in the view. The developers of AngularJS take a stance on this and say that such concerns are better dealt with as the data flows from the controller into the view. In fact, this is why a filter is called a filter; the data is "filtered" as it travels from the controller into the view. Some filters can be much more complex than simple case converters. In the lowercase scenario, we were able to use a single JavaScript method call directly in the controller without things looking messy and out of place, but had we wanted to implement title casing (whereby the first letter of each word is in uppercase and the remainder are in lowercase), things would have gotten a lot more involved and required a much more modular solution. Obviously, having to repeat such logic in each controller or application in which you might need it is not a very DRY approach. ■ Tip the drY principle states that "Every piece of knowledge must have a single, unambiguous, and authoritative representation within a system." an easier way to say this is simply "Don't Repeat Yourself." While it is true that the filter may be added to the view in multiple places, the underlying implementation of that filter need only be written once. Of course, it is up to you to decide how to approach any given situation. Filters are simply an option that you have at your disposal. Nonetheless, filters are a great way to keep your code modular and clean, as they make for a good unit of reuse across AngularJS projects. In fact, as there is a vibrant developer community both contributing to and sharing AngularJS filters online. They make for a good unit of reuse for everyone. ■ Tip a great source of modules (filters, directives, and services) is available at http://ngmodules.org/. Built-in Filters The empowering aspect of filters is, in my opinion, the ability to create your own filters and share them with the rest of the team (or AngularJS community). That being said, AngularJS ships with a very handy set of filters. We will look at these built-in filters now, starting with the number filter. We will look at how to craft a custom filter before the end of this chapter. The Number Filter This filter will help us address another issue with our sample data: the overly precise value of the consumption property (which represents the amount of data that the customer has used for this billing period). Let's make this friendlier by rounding the number of places after the decimal point. Listing 4-4 shows how you can achieve this. Listing 4-4. Rounding Up Values with the Number Filter Listing 4-4

Consumption: {{data.consumption }}
Consumption: {{data.consumption | number }}

Share: