Lesson 13(E).pdf
Document Details
Uploaded by EloquentQuasar
M.E.S. Vasant Joshi College of Arts & Commerce
Tags
Full Transcript
13 JavaScript Libraries for DOM integrations and SPA Lesson Introduction In the previous lesson you have learnt to host and maintain web sites in web server systems. This week you will lean on Single Page Application development with JavaScript framework such as AngularJS. This week focu...
13 JavaScript Libraries for DOM integrations and SPA Lesson Introduction In the previous lesson you have learnt to host and maintain web sites in web server systems. This week you will lean on Single Page Application development with JavaScript framework such as AngularJS. This week focus on various structural components on web to build responsive web widgets. Learning Outcomes: After completion of this lesson, the learner will be able to create Single Page Applications with dynamic interaction libraries. This lesson enable you to Describe DOM and elements Use AngularJS library functions Create Single Page Applications (SPA) using AngularJS library Lesson Outline Document Object Model (DOM) Data Binding UI Logic and controllers Single Page Applications AngularJS Syntax and directives Event driven programing with AngularJS AngularJS APIs AngularJS Animations AJAX 13.1 Document Object Model (DOM) The Document Object Model (DOM) is considered as an application programming interface (API) for HTML and XML documents. In web designing, a web page is loaded, the browser creates itself a Document Object Model of the relevant page. Document Object Model provide these facilities to the programmers. Build documents Navigate their structure Add, edit, or delete functions The HTML DOM model is structured as a tree of Objects: Document Root Element: Element: Element: Element: Attribute: Element: Element: “href” Text: Text: Text: “W3Schools” “Document” “DOM Tree” Using the object model, JavaScript can change all the HTML elements, attributes and CSS styles in the page as well as add or remove existing HTML elements and attributes. JavaScript can react to all existing HTML events and create new events to create dynamic HTML. 13.1.1 HTML DOM Methods There are HTML DOM methods and properties. DOM methods are actions, which can perform on HTML Elements. DOM properties are values, which can set or change of HTML Elements. The following example changes the content (the innerHTML) of the element with id="message". Example: document.getElementById("message").innerHTML = "Welcome to SPA!"; Easiest way to access the HTML element is by using the id of the element. In the above example, getElementById method is used id="message" to find the element. For getting the content of HTML elements we can use the innerHTML property. 13.1.2 JavaScript HTML DOM Document The document object is representing the web page in a structured arrangement. To access any element in the web page, easily start with accessing the document object. The following url provide an explanation with activities on DOM. Please refer the online material. https://www.w3schools.com/js/js_htmldom_document.asp 13.1.3 JavaScript HTML DOM Elements DOM elements provide access to HTML elements in an HTML page. We can find these elements by id, tag name, class name, CSS selectors and HTML object collections. To do more exercises refer the w3schools activities in the following link. https://www.w3schools.com/js/js_htmldom_elements.asp 13.1.4 JavaScript HTML DOM - Changing HTML The Document Object model allows JavaScript to change the content of HTML elements by changing the HTML output stream or changing the HTML content. In JavaScript, document.write() can be used to write directly to the HTML output stream. We can modify the content of an HTML element is by using the innerHTML property. 13.2 UI Logic and Controllers 13.2.1 MVC Architecture MVC architecture is a software design pattern, which can be used for developing web applications. In a simple manner, the controller receives all requests and works with the Model to prepare the data, which is needed by the View. The view used the data prepared by the Controller to the purpose of presentation. The Model: The model is maintaining the data of the web application. It responds to the request from the view (UI) and to the instructions from the controller (Logic). The View: View is a user interface (UI). View display data using model to the user and let users to modify the data. The Controller: Controller handles the user request or operation. Normally, user interacts with the View, using a URL request, this request will be handled by the Controller (logically). The controller extracts the appropriate view with the model data as a response. MVC Architectural Operation Introduction to AngularJS: AngularJS is a structured, JavaScript framework used for dynamic single page applications. As a framework it uses code components written in HTML in order to operate particular function. The data binding and dependency functionalities of Angular JS saves time invested in writing lengthy codes. All these features are packaged in a browser that makes it a suitable server technology. The following video clips provide an introduction and features of Angular. https://www.youtube.com/watch?v=WAZTZUgeLhQ https://www.youtube.com/watch?v=BTF5WrKj2mY 13.3 Data Binding 13.3.1 Two-way Binding Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes the view reflects the change wise-versa when data in the view changes the model is updated. This happens automatically and makes sure that the model and the view is updated all times. Perform the following example and observe the way of operation of AngularJS. Example: Name: Name: {{firstname}} {{lastname}} var app = angular.module('myFirstApp', []); app.controller('myCtrl', function($scope) { $scope.firstname = "Loch"; $scope.lastname = "Rana"; }); Activity 13.1: Study the operation of above angular web page and identify the specialty with respect to the normal JavaScript functionality. Develop a web page to obtain personal details and display those details when they type it. 13.4 Single Page Applications What is a Single Page Application? Single-page application (SPA) is a web application, which offers more dynamic interactions. It interacts with the user by dynamically rewriting the requested page rather than loading entire new pages from a server. In an SPA, all the necessary code such as HTML, JavaScript, and CSS is retrieved with a single page load. Otherwise the relevant resources are dynamically allocated to the page as necessity, for the response to user actions. What is the difference between a regular website and an SPA? Major difference between regular web site and SPA is the reduced amount of page refreshes. SPAs have a heavier usage of AJAX (AJAX is a significant way to communicate with back-end servers without refreshing the entire page to get details loaded into the application.). What are the major benefits of SPAs? One is there is no page change when clicking on a link. In an SPA, the navigation controls and main interface normally stay on the page by clicking a link, only the piece of content (elements) to be changed actually gets changed. Next benefit is getting a lighter server response payload compare to the load of whole page data from the server. This is a major advantage when considering the network traffic. Popular JavaScript Frameworks for Building SPAs There are a lot of open source JavaScript frameworks that help with building SPAs, such as: Angular React Ember Aurelia Vue.js Cycle.js Backbone 13.5 AngularJS Features, Syntax and directives 13.5.2What are the features? AngularJS is a powerful web development framework to create RICH Internet Application(RIA) It facilitates to write client side application using MVC architecture AngularJS automatically handles JavaScript code fit for each browser AngularJS is open source framework and it is licensed under the Apache License version 2.0. Core Features Refer the following link for the core features. https://www.tutorialspoint.com/angularjs/angularjs_overview.htm 13.5.3Advantages of AngularJS Able to create Single Page Application (SPA) in a proper way Has data binding capability which is giving user a rich and responsive experience Code is unit testable It uses dependency injection and make use of separation of concerns Provides reusable components Write less code and get more functionality Applications can run on all major browsers and smart phones 13.5.4 Disadvantages of AngularJS Not Secure Not degradable 13.5.5 AngularJS Expressions AngularJS expressions can be written inside double braces like below. {{ expression }} AngularJS expressions can also be written inside a directive like this. ng-bind="expression" AngularJS can resolve the expression, and return the result exactly where the expression is written. AngularJS expressions are much like JavaScript expressions. They can contain literals, operators, and variables. Example: {{ 5 + 5 }} or {{ firstName + " " + lastName }} My first expression: {{ 5 + 5 }} If you remove the ng-app directive, HTML will display the expression as it is, without solving it: Example My first expression: {{ 5 + 5 }} You can write expressions wherever you like, AngularJS will simply resolve the expression and return the result. Example: Let AngularJS change the value of CSS properties. Change the color of the input box below, by changing its value, the relevant code snippet is given below. lightblue Activity 13.2: Design a web page with a text box to change the color of text according to the entered color in the text box by using the above code snippet. AngularJS Numbers AngularJS numbers are like JavaScript numbers: Example Total in dollar: {{ quantity * cost }} Same example using ng-bind: Example Total in dollar: Using ng-init is not very common. Activity 13.3: Develop a single page web application to calculate a bill according to a list of stored items, unit prices and when entering the quantity in item wise input boxes, to automatically calculate the bill. AngularJS Strings AngularJS strings are like JavaScript strings: Example The name is {{ firstName + " " + lastName }} Same example using ng-bind: Example The name is AngularJS Objects AngularJS objects are like JavaScript objects: Example The name is {{ person.lastName }} Same example using ng-bind: Example The name is AngularJS Arrays AngularJS arrays are like JavaScript arrays: Example The third result is {{ points }} Same example using ng-bind: Example The third result is Activity 13.4: Create test applications for the above given code snippet to observe the behaviors of above example starting from Angular Strings. 13.6 AngularJS Directives AngularJS has a set of built-in directives. These directives provide functionality to the web applications. User defined directives also acceptable. AngularJS directives are extended HTML attributes with the prefix ng-. The ng-app directive initializes an AngularJS application The ng-init directive initializes application data The ng-model directive binds the value of HTML controls (input, select, textarea) to application data Example Country: You wrote: {{ country }} The ng-app Directive The ng-app directive defines the root element of an AngularJS application and it will automatically initialize when the web page is loaded. The ng-init Directive The ng-init directive defines initial values for an AngularJS application. The ng-model Directive The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. The ng-model directive can also: Provide type validation (number, email, required) for application data. Provide status (invalid, dirty, touched, error) for application data. Provide CSS classes for HTML elements and bind HTML elements to HTML forms. Repeating HTML Elements Consider this ng-repeat directive, it repeats an HTML element. Example {{ x }} Activity 13.5: Create test applications for the above given code snippet to list down an array of names with their indexes. Create New Directives Angular provides facilities to create your own directives. New directives are created by using the.directive function. Make an HTML element with the same tag name as the new directive. You must consider that, when naming a directive, you must use a camel case name such as simpleTestDirective, but when invoking it, you must use -separated name such as simple-test-directive. The following example shows one application. var app = angular.module("myFirstAngularApp", []); app.directive("simpleTestDirective", function() { return { template : "Made by a directive!" }; }); You can invoke a directive by using: Element name Attribute Class Comment The legal restrict values are: E - Element name A - Attribute C - Class M - Comment By default the value is EA, meaning that both Element names and attribute names can invoke the directive. By adding a restrict property with the value "A", the directive can only be invoked by attributes. Example var app = angular.module("myFirstAngularApp", []); app.directive("simpleTestDirective", function() { return { restrict : "A", template : "Made by a directive!" }; }); 13.7 Event driven programing with AngularJS Events driven programming is modeled on human application dialog. Interaction controls the flow of the program which determined by the occurrence of events. These events are monitored by code known as an event listener that, if it detects that its assigned event has occurred, runs an event "handler", typically a callback function or method. Improved responsiveness and flexibility Just like CURD (Create, Retrieve, Update and Delete), it has focused on data presentation and two-way data binding. Thus, AngularJS happens to be classically well suited as the frontend framework for the web application developed over RESTful API. Using AngularJS makes setting up an event-driven architecture to augment an underlying data API a very straightforward process. It makes it easy to enforce application’s data integrity and ensure that all changes are present in the underlying data store when it happens, rather than at a future synchronization point. For more details go through the content of the following links https://www.letsnurture.com/blog/making-web-applications-angularjs.html Activity 13.6: Perform the exercise activities given in the following tutorial. https://www.w3schools.com/angular/angular_intro.asp 13.8 AngularJS APIs The documentation is organized into modules, which contain various components of an AngularJS application. These components are directives, services, filters, providers, templates, global APIs, and testing mocks. There is also a guide with articles on various topics, and a list of external resources. You can follow up angularJS API from this link. https://docs.angularjs.org/api 13.9 AngularJS Animations AngularJS provides animated transitions, with help from CSS. AngularJS provides animation facility for common directives such as ngRepeat, ngSwitch, and ngView, as well as custom directives via the $animate service. These animation facilities are set in place to trigger animations during the life cycle of various directives and when triggered, will attempt to perform a CSS Transition, CSS Keyframe Animation or a JavaScript callback Animation For more details and exercises please refer below links. https://www.w3schools.com/angular/angular_animations.asp https://docs.angularjs.org/tutorial/step_14 13.10 AJAX When obtaining some kind of information from a database or send user details to a server we have to make an HTML form and GET or POST data to the server. Client has to click the “Submit” button to send or get the relevant information also wait for the server to respond and finally a relevant page will load as the results. The server returns a new page each time the user submits input therefore, web applications can run slowly it means less user-friendly. With AJAX JavaScript communicates directly with the server through the JavaScript XMLHttpRequest object. With an HTTP request, a web page can make a request and get a response from a web server, without reloading the page. The client will stay on the same page and does not notice that scripts request pages as well as send data to a server in the background. AJAX stands for Asynchronous JavaScript and XML. For an example, when you type something in google search, it suggests a list according to the changes you do in your typed text. This happens through AJAX. How AJAX works? AJAX communicates with the server using XMLHttpRequest object. These are the steps that you can learn how AJAX works? 1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object. 2. HTTP Request is sent to the server by XMLHttpRequest object. 3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc. 4. Data is retrieved. 5. Server sends XML data or JSON data to the XMLHttpRequest callback function. 6. HTML and CSS data is displayed on the browser. AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses these things to display dynamic content - XHTML for content, CSS for presentation, along with Document Object Model and JavaScript. After hitting submit, and getting directed to a new page with new information from the server. With AJAX, when you press submit button, JavaScript will make a request to the server and take the results then update the current screen. So, the user would never know about the back end process. XML is used for receiving server data. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. Clicking is not required, mouse movement is a sufficient event trigger. Data-driven as opposed to page-driven. Activity 13.7: Do the following tutorial on AJAX with the given interactive examples. https://www.w3schools.com/xml/ajax_intro.asp Summary Now you have completed learning lesson 13. We have discussed about creating dynamic, responsive Rich Web Applications with AngularJS.