Modern Web Application Development Single Page Application Development using AngularJS JavaScript Overview Static Page:
Views 113 Downloads 23 File size 3MB
Modern Web Application Development Single Page Application Development using AngularJS JavaScript Overview Static Page: The web isn’t always as responsive as it could be. You would expect entering data in a web page would generate some sort of response… but nothing happened. Interaction is two-way communication. But JavaScript Talks Back. JS turns a web page into an interactive. JavaScript brings a web page to life by allowing it to respond to a user’s input. JS can turn a web page interactive application as opposed to a static, life less page. Example:
Modern Web Page JS sits with HTML and CSS as one of three pieces of Modern Web Page Construction. HTML provides the Structure CSS adds the Style JS puts the action (injection functional sizzle, allowing the page to take action). JS springs into action when the user asks the page to perform a task. Your Web browser can handle HTML, CSS and JavaScript. Alerting the user the with a function. JS alert() function and passing it the text you want to display. JS alert() is a pop-up window, or box, that you can use to display information to the user. Functions are reusable piece of code that perform common tasks. Data Types: JS uses three basic data types: text, number, and boolean. var variablename = initial value; // variable names use CamelCase lowerCamelCase is used to name multiWord variables. the first word is all lowercase, but additional words are mixed-case. const constantname = constant value; A piece of data is undefined when it has no value. X = NaN; NaN is a value that isn’t a number even though you’re expecting the value to be one. parseInt() and parseFloat() converts text to a number. Use getElementById() to grab the data from your Web page. The key to accessing a web page element with JavaScript is the id attribute of the HTML tag:
The id attribute is what you use to access the form field in JavaScript code The id attribute uniquely identifies any element in a page. The name attribute uniquely identifies a field within a form.
isNan() function Client’s window width and height The client window is only the part of the browser window that displays a web page. document.body.clientWidth document.body.clientHeight Script Life Cycle 1. The browser is launched 2. User enters URL in address bar 3. The page is loaded from the web server – HTML, CSS, JS and all 4. The onLoad event fires, JavaScript variables are created and initiated. 5. The user closes the browser or reloads the page 6. The script stops, JS cleans up all variables, and the page is closed. Scope of variables: Global Variables data can be seen everywhere in a script
Local Variables limited to specific block of code, such as a function Arrays stores multiple pieces of data in a single place. var showtime = new Array(); showtime*0+ = “12:30”; var showTime = *“12:30”, “2:45”, “5:00”, “7:00”+; Functions function name() { body } Passing information to functions: function name(arguments) { body } Returning data from functions: return value; Callback Functions: Which are called by the browser, instead of your own code. The most common use of callback functions is in handling events.
Using Function References You can assign a function reference directly in a JS code. window.onload = initSeats; // There are no parantheses following the function name because you don’t want to run the function; you just want to reference it. Anonymous Functions: It is a nameless function that handles the event. window.load = function() { initSeats(); } document.getElementById(“seat26”).onclick = function(evt) , showStatus(26); } An event object is passed into event handler, in this case evt argument. The event object contains information specific to each different event. Regular Expressions A regular expression is used to match patterns in text. Pattern involves physical attributes of a person. Pattern = Tall, no glasses, short hair. The pattern describes physical properties of a person that are then matched against actual people. Regular expressions allow you to do the same kind of pattern matching with strings. A text pattern involves a certain sequence of characters. Pattern = ##### This pattern involves a sequence of exactly five numeric digits. All Regular Expressions are enclosed by forward slashes. / expression / Within the expression, a collection of special symbols known as metacharacters are used in conjunction with letters and numbers. (dot) . Any character other than a new line \d Any numeric digit \w Any alphanumeric character \s A whitespace character
^ String must begin with the pattern (The string being matched can’t have any text preceding the pattern) $ The String must end with the pattern. (The pattern must be the very last characters in the string). Examples: /./ (Any Single Character) “A” or “%” or “7” /\w/ (Any Alphanumeric) “A” or “7” /\d/ (A single digit) “7” or “2nite” or “catch22” /^\d/ (One digit at the beginning of a string) “7” or “007” or “2nite” /\d\d$/ (Two digits at the end of a string) “catch22” /\d\d\d/ (Three digits in a row) “007” /^cat/ (cat appearing at the beginning of a string) “catch22” /cat$/ (cat appearing at the end of a string) “incat” /^\d\d\d\d\d-\d\d\d\d$/
Quantifiers precede within a regular expression, and provide control over how many times a subpattern appears in a pattern. {n} sub-pattern must appear exactly n times in a row. * sub-pattern is optional and can appear any number of times ? sub-pattern is optional, but can only appear once if does appear + sub-pattern is required, and can appear any number of times () used to group together sub-patterns much as you group together mathematical expns Examples /^\d{5}-\d{4}$/ /\w*/ /.+/ /(Hot)? ?Donuts/
A zip code pattern. Matches any number of alphanumeric characters, including an empty string Any character must appear one or more times… matches a non-empty string Matches either “Donuts” or “Hot Donuts”
Validating data with regular expression var regex = /^\d{5}$/; The regular expression matches a 5-digit ZIP code. $: This object literal automatically creates a RegEx object. If(!regex.test(inputField.value)) // The zip code is invalid Date pattern: MM/DD/YYYY or MM/DD/YY /^\d{2}\/\d{2}\/\d{2,4}$/ Phone Number pattern: \^\d{3}-\d{3}-\d{4}$/ Email: /^\w+@\w+\.\w{2,3}$/ Creating space with DIV In order to display description on the page instead of alert box, we first need to define a physical area on the page as an HTML element. should work fine for description text appears as its own paragraph.
innerHTML is used to set the content on the page. document.getElementById(“sometext”).innerHTML = “You are not alone”; The DOM sees a web page as a hierarchical tree of nodes. Your page is a collection of DOM nodes. DOM nodes are classified according to their node types.
Climbing the DOM tree with properties: nodeValue The value stored in a node, only for text and attribute nodes (note elements) nodeType The type of a node, such as DOCUMENT or TEXT, but expressed as a number. childNodes Arrays containing all of the child nodes beneath a node, in the order that the nodes appear in the HTML code. firstChild The first child node beneath a node. lastChild The last child node beneath a node. Document.getElementById(“sometext”).nodeValue
Objects link variables (properties) and functions (methods) together inside a storage container. The dot operator references a property or method from an object A constructor is responsible for creating an object. Every custom object requires its own constructor, which is named the same as the object. Example: Write a constructor for a Blog object that creates and initializes properties for the date and body text of a blog entry. Function Blog(body, date) { this.body = body; this.date = date; } var blogEntry = new Blog(“Got the new cube”, “08/04/2013”); An Object class is a template, while an object instance is the thing created from the template. Defining Objects: function Card(name, address, work, home) { this.name = name; this.address = address; this.workphone = work; this.homephone=home; } Defining a Object method function PrintCard() { line1 = "Name: "+ this.name + "
\n"; line2 = "Address: " + this.address + "
\n"; line3 = "Work Phone: " + this.workphone + "
\n"; line4 = "Home Phone: " + this.homephone + "\n"; document.write(line1, line2, line3, line4); }
You now have a function that prints a card, but it isn't officially a method of the Card object. The last thing you need to do is make PrintCard() part of the function definition for Card objects. Here is the modified function definition: function Card(name,address,work,home) { this.name = name; this.address = address; this.workphone = work; this.homephone = home; this.PrintCard = PrintCard; }
The following statement creates a new Card object called tom:
tom = new Card("Tom Jones", "123 Elm Street", "555-1234", "555-9876"); tom.PrintCard();
Extending Built-In Objects:
JavaScript includes a feature that enables you to extend the definitions of built-in objects. For example, if you think the String object doesn't quite fit your needs, you can extend it, adding a new property or method. This might be very useful if you were creating a large script that used many strings. You can add both properties and methods to an existing object by using the prototype keyword. (A prototype is another name for an object's definition, or constructor function.) The prototype keyword enables you to change the definition of an object outside its constructor function. As an example, let's add a method to the String object definition. You will create a method called heading, which converts a string into an HTML heading. The following statement defines a string called title: title = "Fred's Home Page";
This statement would output the contents of the title string as an HTML level 1 heading: document.write(title.heading(1));
Listing 6.4 adds a heading method to the String object definition that will display the string as a heading, and then displays three headings using the method. Listing 6.4. Adding a Method to the String Object
Test of heading method
First, you define the addhead() function, which will serve as the new string method. It accepts a number to specify the heading level. The start and stop variables are used to store the HTML "begin header" and "end header" tags, such as and . After the function is defined, use the prototype keyword to add it as a method of the String object. You can then use this method on any String object or, in fact, any JavaScript string. This is demonstrated by the last three statements, which display quoted text strings as level 1, 2, and 3 headers. function Name(first,last) { this.first = first; this.last = last; }
You can add additional properties to an object you have created just by assigning them: Fred.middle = "Clarence";
Properties you add this way apply only to that instance of the object, not to all objects of the type. A more permanent approach is to use the prototype keyword, which adds a property to an object's prototype (definition). This means that any future object of the type will include this property. You can include a default value: Name.prototype.title = "Citizen";
Object Oriented Java Script Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented or instance-based programming. Java Script Object oriented programming – Custom Object The Class: JS is a prototype-based language which contains no class statement, such as is found in C++ or Java. Instead JS uses functions as classes. Defining a class is easy as defining a function. Function Person() { } The Object (Class Instance) To create a new instance, use new operator. var p1 = new Person(); var p2 = new Person(); The constructor is called at the moment of instantiation. The Property properties are variables contained in the class. Properties defined within a class is done by keyword this, which refers to the current object. function Person(gender) { this.gender = gender; alert(‘Person instantiated’); } var p1 = new Person(‘Male’); alert(‘Person 1 is a ‘ + p1.gender); The Methods are functions and they are defined as functions. To define a method, assign a function to a named property of the class’s prototype property; the name that the function is assigned to is the name that the method is called by on the object. Person.prototype.sayHello = function() { Alert(‘Hello method..’); }
In JavaScript methods are regular function objects that are bound to a class/object as a property which means they can be invoked "out of the context". Consider the following example code: function Person(gender) { this.gender = gender; } Person.prototype.sayGender = function() { alert(this.gender); }; var person1 = new Person('Male'); var genderTeller = person1.sayGender; person1.sayGender(); // alerts 'Male' genderTeller(); // alerts undefined alert(genderTeller === person1.sayGender); // alerts true alert(genderTeller === Person.prototype.sayGender); // alerts true This example demonstrates many concepts at once. It shows that there are no "per-object methods" in JavaScript since all references to the method point to the exact same function, the one we have defined in the first place on the prototype. JavaScript "binds" the current "object context" to the special "this" variable when a function is invoked as a method(or property to be exact) of an object. This is equal to calling the function object's "call" method as follows: genderTeller.call(person1); //alerts 'Male' Inheritance Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single class inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance. JavaScript does not detect the child class prototype.constructor see Core JavaScript 1.5 Reference:Global Objects:Object:prototype property, so we must state that manually. In the example below, we define the class Student as a child class of Person. Then we redefine the sayHello() method and add the sayGoodBye() method. // define the Person Class function Person() {} Person.prototype.walk = function(){ alert ('I am walking!'); }; Person.prototype.sayHello = function(){ alert ('hello'); }; // define the Student class
function Student() { // Call the parent constructor Person.call(this); } // inherit Person Student.prototype = new Person(); // correct the constructor pointer because it points to Person Student.prototype.constructor = Student; // replace the sayHello method Student.prototype.sayHello = function(){ alert('hi, I am a student'); } // add sayGoodBye method Student.prototype.sayGoodBye = function(){ alert('goodBye'); } var student1 = new Student(); student1.sayHello(); student1.walk(); student1.sayGoodBye(); // check inheritance alert(student1 instanceof Person); // true alert(student1 instanceof Student); // true Using Object.create the inheritance line would instead be: Student.prototype = Object.create(Person.prototype);
AngularJS
AngularJS is a client-side JavaScript framework It's used to build web applications It is prescriptive Makes creating a user interface (UI) easier through data-binding It helps organize and architect an application it has custom elements and attributes it uses dependency injection
What is AngularJS? AngularJS is a framework that helps you build front-ends for web-based applications. AngularJS is a prescriptive client-side JavaScript framework used to make single-page web apps. Note: Prescriptive Architecture vs. Descriptive Architecture A system’s prescriptive architecture captures the design decisions made prior to the system’s construction. It is the as-conceived or as-intended architecture. A system’s descriptive architecture describes how the system has been built. It is the asimplemented or as-realized architecture. AngularJS is prescriptive in the sense that it has a recommended way of building web apps. It has its own spin on the ubiquitous Model View Controller (MVC) pattern that is especially well suited for JavaScript. In this way, Angular is prescribing a way for you to divide your application up into smaller parts. AngularJS is a framework that runs in the web browser. AngularJS is for single page apps, meaning the browser only loads the page once, but then makes asynchronous calls to the server to fetch new information. Here asynchronous means that the application can continue to function without having to stop and wait for the server to respond. Core Features of AngularJS Two-way Data Binding: Let's say you have a form to store user contact info and you want to update the addresses input box when data is returned from the server. You could do the following: document.getElementById('yourName')[0].text = 'bob'; You manually seek to the element you want to change, calling a long, awkward series of DOM methods. You also have to make this call every time something causes the address to change. If we take the same example above and use data-binding we accomplish the same thing but faster. Here's our example with data-binding: {{yourName}} var yourName = 'bob'; Model View Whatever (MVW): MVC is a pattern for dividing an application into different parts (called Model, View, and Controller), each with distinct responsibilities.AngularJS as a "Model View Whatever" framework. In AngularJS, the View is simply your HTML with the AngularJS syntax compiled into it. Once the initial compilation cycle completes, the View can then bind to the object which is essentially the ViewModel.
HTML Templates: HTML templates are useful when you want to predefine a layout with dynamic sections to be filled in it is connected with an appropriate data structure. An example of this would be if you wanted to repeat the same DOM element over and over in a page such as a list or a table. You would define what you want a single row to look like and then attach a data structure, such as a JavaScript array, to it. The template would repeat each row for as many items in the array filling in each instance with the values of that current array item. There are plenty of templating libraries out there but most of them require you learn a new syntax. AngularJS templates are HTML and are validated by the browser just like the rest of the HTML in the page. Deep Linking: Dependency Injection: Defined a function that accepts a parameter you have leveraged dependency injection. You are injecting something that your function depends on to complete its work. Consider this code: Defining functions without DI function a () { return 5; } function b () { return a() + 1; } console.log(b()); Defining functions with DI service('a', function () { return 5; }); service('b', function (a) { return a() + 5; });
service('main', function (b) { console.log(b()); }); Overriding with DI // swap out 'b' easily by redefining it in another file: service('b', function (a) { return 1; // this is a test value }); Directives: it allows you to extend HTML to do some really powerful things. Directives provide the perfect way to merge the declarative nature of HTML and the functional nature of JavaScript into one place. Let's say you're writing an application that has a dropdown.
{{greeting}} {{person}}
You can edit your profile details below.
Email Address