• Objectives: Basic Web Application Model Web Development Frameworks/Languages • Resources: Web Frameworks Popular Frameworks 10 Things to Know Angular React Knockout • Videos: Rest Postman Chrome Developer Tools LECTURE 32: INTRO TO WEB DEVELOPMENT
Principles of Web Design Availability Performance Reliability Scalability Manageability Cost
Core Components of Web Applications UI (Front End (DOM, Framework)) Request Layer (Web API) Back End (Database, Logic) Internet Browser Media Cache API Front End JSON Database Logic ClientServer
FRONTEND DEVELOPMENT
Front End Languages HTML/CSS Javascript Java (applets) What is the most popular? Answer: Javascript/HTML/CSS is the only real option for front-end native languages and is basically the standard. But there are many variations on JavaScript that are used.
DOM (Document Object Model) Document Object Model makes every addressable item in a web application an Object that can be manipulated for color, transparency, position, sound and behaviors. Every HTML Tag is a DOM object
DOM (Document Object Model) DOM CSS HTML JavaScript
What is a Framework? Software Framework designed to reduce overhead in web development Types of Framework Architectures Model-View-Controller (MVC) Push vs Pull Based Most MVC Frameworks user push-based architecture “action based” (Django, Ruby on Rails, Symfony, Stripes) Pull-based or “component based” (Lift, Angular2, React) Three Tier Organization Client (Usually the browser running HTML/Javascipt/CSS) Application (Running the Business Logic) Database (Data Storage) Types of Frameworks Server Side: Django, Ruby on Rails Client Side: Angular, React, Vue
FrameworkFramework DOM CSS HTML JavaScript
Javascript Frameworks AngularJS/Angular 2 ASP.net React Polymer 1.0 Ember.js Vue.js
MVC (Model View Controller) A Web Application Development Framework Model (M): Where the data for the DOM is stored and handled) This is where the backend connects View (V): Think of this like a Page which is a single DOM Where changes to the page are rendered and displayed Control (C): This handles user input and interactions Buttons Forms General Interface
MVC Model Controller Model View
BACKEND DEVELOPMENT
What is a Backend? All of the awesome that runs your application. Web API Connection layer between the frontend and backend Connected through API calls (POST, GET, PUT, etc. ) Transmit Content from the Backend to the Frontend commonly in JSON Blobs Service Architecture that drives everything (Where all the logic is)
What is a WebAPI? The intermediate layer between front end and back-end systems A “must have” if your APIs will be consumed by third-party services Attention to details: How consumable is the API (signature, content negotiation)? Does it comply with standards (response codes, etc.)? Is it secure? How do you handle multiple versions? Is it truly RESTful?
Representational State Transfer (REST) Client-server Stateless Resource-based (vs. remote procedure call) HTTP methods (GET, POST, PUT, DELETE) Side Effects It’s a style, not a standard Don’t hate on HATEOAS
WebAPI Terms GET – “read” POST – “insert” (collection) PUT – “replace” DELETE – “remove” PATCH – “update” Custom (proceed with caution)
Web Status Codes 200 – OK – things are great (return the item) 201 Created – after POST (HATEOAS – return location) 204 No Content (i.e. successful DELETE) 400 – Bad Request (validation error, missing parms, etc.) 401 – Unauthorized – Who are you? 403 – Forbidden – No soup for you 404 – Not Found
What is Angular MVC Structure Framework Single Page Application (SPA) Client Side Template Testing
Building Blocks Directives Component – Templates (HTML), Styles (CSS), & Logic (JavaScript) Attribute – Styling HTML Structural – Manipulating HTML Data Flow Interpolation – Variable Printing in Templates Event Binding – Trigger Events 2-Way Binding – Variables updated in real time Providers Services Reusable Logic Data Storing and Manipulation Libraries
Component Directives "…reusable building blocks for an application" Components have: HTML CSS JavaScript
JavaScript – 1995 Netscape ECMAScript Standard – June 1997 Garret coins Ajax - 2005 Prototype, Dojo, jQuery –ECMAScript 5 – 20092005/2006 JSON Support History
AngularJS – 2009 React – 2011 Facebook NewsFeed React – 2013 Open Sourced AngularJS 2.0 – Announced Sept 2014 Breaking changes ECMAScript 6 – June 2016 History
From the fine folks at Google AngularJS 1.x – Google JavaScript library for development AngularJS 2.x – Called Angular Angular is a Framework Angular is opinionated Angular has code in your markup Angular is HTML centric AngularJS
Angular is a Framework. React is a Library Not The Same
Mobile First Standards focused Performance Virtual Dom Web Components Angular – Why
import { Component } from 'angular2/core'; @Component({ selector: 'foo-Div', templateUrl: 'app/foo.html', styleUrls: [ 'app/foo.css' ] }) export class Foo { public message = 'Foo!'; } Component Angular
Angular separate HTML file React HTML is in render method •JSX allows for HTML like Angular has one way and two way data binding •{{element.name}} •<input type="text" [(ngModel)]="inputFieldName" id="id1" /> React is stateless, no two way binding •This.state.inputFieldName Templates and Databinding
Rise of the Responsive Single Page App
Responsive • Unified across experiences • Can be embedded as mobile app • Better deployment and & maintanence • Mobile users need to get access to everything Image: http://coenraets.org/blog/wp-‐content/uploads/2011/10/directory11.png
Single-‐pageApplications (SPA) • Web app that fits on a single web page – Fluid UX, like desktop app – Examples like Gmail, Google maps • Html page contains mini-‐views(HTML Fragments) that can be loaded in the background • No reloading of the page, • Requires handling of browser history, navigation and bookmarks
JavaScript • SPAs are implemented using JavaScript and HTML
Challenges in SPA • DOM Manipulation – How to manipulate the view efficiently? • History – What happens when pressing back button? • Routing – Readable URLs? • Data Binding – How bind data from model to view? • View Loading – How to load the view? • Lot of coding! You could use a framework instead ...
Single-page Application Single page apps typically have “application like” interaction dynamic data loading from the server-side API fluid transitions between page states more JavaScript than actual HTML They typically do not have support for crawlers (not for sites relying on search traffic) support for legacy browsers (IE7 or older, dumbphone browsers)
SPAs Are Good For … • “App-like user experience” • Binding to your own (or 3rd party) RESTful API • Replacement for Flash or Java in your web pages • Hybrid (native) HTML5 applications • Mobile version of your web site The SPA sweet spot is likely not on web sites, but on content-rich cross-platform mobile apps
PJAX Pjax is a technique that allows you to progressively enhance normal links on a page so that clicks result in the linked content being loaded via Ajax and the URL being updated using HTML5 pushState, avoiding a full page load. In browsers that don't support pushState or that have JavaScript disabled, link clicks will result in a normal full page load. The Pjax Utility makes it easy to add this functionality to existing pages.
SPAs and Other Web App Architectures Server-side Server-side + AJAX PJAX SPA What Server round-trip on every app state change Render initial page on server, state changes on the client Render initial page on server, state changes on server, inject into DOM on client-side Serve static page skeleton from server; render every change on client-side How UI code on server; links & form posting UI code on both ends; AJAX calls, ugly server API UI code on server, client to inject HTTP, server API if you like UI code on client, server API Ease of development UX & responsiveness Robots & old browsers Who’s using it? Amazon, Wikipedia; banks, media sites etc. Facebook?; widgets, search Twitter, Basecamp, GitHub Google+, Gmail, FT; mobile sites, startups
Angular JS • Single Page App Framework for JavaScript • Implements client-‐sideMVC pattern – Separation of presentation from business logic and presentation state • No direct DOM manipulation, less code • Support for all major browsers • Supported by Google • Large and fast growing community
AngularJS – Main Concepts • Templates • Directives • Expressions • Data binding • Scope • Controllers • Modules • Filters • Services • Routing
Anatomy of a Backbone SPA • Application as a ‘singleton’ reference holder • Router handles the navigation and toggles between views • Models synchronize with Server API • Bulk of the code in views • All HTML in templates
Architecture
SPA Client-Server Communication • HTML and all the assets are loaded in first request • Additional data is fetched over XMLHTTPRequest • If you want to go real-time, WebSockets (socket.io) can help you
HOW IT WORKS?
HOW IT WORKS?
Basic Concepts • 1) Templates – HTML with additional markup, directives, expressions, filters ... • 2) Directives – Extend HTML using ng-app, ng-bind, ng-model • 3) Filters – Filter the output: filter, orderBy, uppercase • 4) Data Binding – Bind model to view using expressions {{ }}
First Example – Template <!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angu lar.min.js"></script> </head> <body> <div ng-app> <!-- store the value of input field into a variable name --> <p>Name: <input type="text" ng-model="name"></p> <!-- display the variable name inside (innerHTML) of p --> <p ng-bind="name"></p> </div> </body> </html> Template
2) Directives • Directives apply special behavior to attributes or elements in HTML – Attach behaviour, transform the DOM • Some directives – ng-app • Initializes the app – ng-model • Stores/updates the value of the input field into a variable – ng-bind • Replace the text content of the specified HTML with the value of given expression
About Naming • AngularJS HTML Compiler supports multiple formats – ng-bind • Recommended Format – data-ng-bind • Recommended Format to support HTML validation – ng_bind, ng:bind, x-ng-bind • Legacy, don't use
Lot of Built in Directives • ngApp • ngClick • ngController • ngModel • ngRepeat • ngSubmit • ngDblClick • ngMouseEnter • ngMouseMove • ngMouseLeave • ngKeyDown • ngForm
2) Expressions • Angular expressions are JavaScript-‐likecode snippets that are usually placed in bindings – {{ expression }}. • Valid Expressions – {{ 1 + 2 }} – {{ a + b }} – {{ items[index] }} • Control flow (loops, if) are not supported! • You can use filters to format or filter data
Example <!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">< /script> </head> <body> <div ng-app> <p>Number 1: <input type="number" ng-model="number1"></p> <p>Number 2: <input type="number" ng-model="number2"></p> <!-- expression --> <p>{{ number1 + number2 }}</p> </div> </body> </html> Directive Expression Directive
ng-‐initand ng-‐repeat directives <!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min .js"></script> </head> <body> <div data-ng-init="names = ['Jack', 'John', 'Tina']"> <h1>Cool loop!</h1> <ul> <li data-ng-repeat="name in names">{{ name }}</li> </ul> </div> </body> </html>
3) Filter • With filter, you can format or filter the output • Formatting – currency, number, date, lowercase, uppercase • Filtering – filter, limitTo • Other – orderBy, json
Using Filters -‐Example <!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">< /script> </head> <body> <div data-ng-init="customers = [{name:’tina'}, {name:’jack'}]"> <h1>Cool loop!</h1> <ul> <li data-ng-repeat="customer in customers | orderBy:'name'"> {{ customer.name | uppercase }}</li> </ul> </div> </body> </html> Filter Filter
Using Filters -‐Example <!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div data-ng-init= "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]"> <h1>Customers</h1> <ul> <li data-ng-repeat="customer in customers | orderBy:'name' | filter:'john'">{{ customer.name | uppercase }}</li> </ul> </div> </body> </html>
Using Filters – User Input Filters the Data <!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">< /script> </head> <body> <div data-ng-init= "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]"> <h1>Customers</h1> <input type="text" data-ng-model="userInput" /> <ul> <li data-ng-repeat="customer in customers | orderBy:'name' | filter:userInput">{{ customer.name | uppercase }}</li> </ul> </div> </body> </html>
API Reference https://docs.angularjs.org/api/ng/filter/filter
VIEWS, CONTROLLERS, SCOPE
Model – View -‐Controllers • Controllers provide the logic behind your app. – So use controller when you need logic behind your UI • AngularJS apps are controller by controllers • Use ng-‐controllerto define the controller • Controller is a JavaScript Object, created by standard JS object constructor
Model – View -‐Controllers a controller is a JavaScript function ○ It contains data ○ It specifies the behavior ○ It should contain only the business logic needed for a single view.
View, Controller and Scope View (html fragment) Controller$scope $scope is an object that can be used to communicate between View and Controller
Scope
<!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ ajax/libs/angularjs/1.4.8/angular.min.js"> </script> </head> <body> <div data-ng-app="myApp" data-ng-controller="NumberCtrl"> <p>Number: <input type="number" ng-model="number"></p> <p>Number = {{ number }}</p> <button ng-click="showNumber()">Show Number</button> </div> <script> var app = angular.module('myApp', []); app.controller('NumberCtrl', function($scope) { $scope.number = 1; $scope.showNumber = function(){ window.alert( "your number= " + $scope.number ); }; }); </script> </body> </html>
Modules • Module is an reusable container for different features of your app – Controllers, services, filters, directives... • If you have a lot of controllers, you are polluting JS namespace • Modules can be loaded in any order • We can build our own filters and directives!
When to use Controllers • Use controllers – set up the initial state of $scope object – add behavior to the $scope object • Do not – Manipulate DOM (use databinding, directives) – Format input (use form controls) – Filter output (use filters) – Share code or state (use services)
App Explained • App runs inside ng-app (div) • AngularJS will invoke the constructor with a $scope – object • $scope is an object that links controller to the view
MODULES, ROUTES, SERVICES
Example: Own Filter // declare a module var myAppModule = angular.module('myApp', []); filter // configure the module. // in this example we will create a greeting myAppModule.filter('greet', function() { return function(name) { ' + name + '!';return 'Hello, }; });
HTML using the Filter <div ng-app="myApp"> <div> {{ 'World' | greet }} </div> </div>
Template for Controllers // Create new module 'myApp' using angular.module method. // The module is not dependent on any other module var myModule = angular.module('myModule', []); myModule.controller('MyCtrl', function ($scope) { // Your controller code here! });
Creating a Controller in Module var myModule = angular.module('myModule', []); myModule.controller('MyCtrl', function ($scope) { var model = { "firstname": "Jack", "lastname": "Smith" }; $scope.model = model; $scope.click = function() { alert($scope.model.firstname); }; });
<!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script <script src="../angular.min.js"></script> src="mymodule.js"></script> </head> <body> <div ng-app="myModule" <div ng-controller="MyCtrl"> <p>Firstname: <input type="text" ng-model="model.firstname"></p> <p>Lastname: <input type="text" ng-model="model.lastname"></p> <p>{{model.firstname + " " + model.lastname}}</p> <button ng-click="click()">Show Number</button> </div> </div> </body> </html> This is now the model object from MyCtrl. Model object is shared with view and controller
ROUTING
Routing • Since we are building a SPA app, everything happens in one page – How should back-‐button work? – How should linking between "pages" work? – How about URLs? • Routing comes to rescue!
<html data-ng-app="myApp"> <head> <title>Demonstration of Routing - index</title> <meta charset="UTF-8" /> src="../angular.min.js" type="text/javascript"></script> src="angular-route.min.js" type="text/javascript"></script> src="myapp.js" type="text/javascript"> <script <script <script </script> </head> <body> <div data-ng-view=""></div> </body> </html> The content of this will change dynamically We will have to load additional module
// This module is dependent on ngRoute. Load ngRoute // before this. var myApp = angular.module('myApp', ['ngRoute']); views. // Configure routing. myApp.config(function($routeProvider) { // Usually we have different controllers for different // In this demonstration, the controller does nothing. $routeProvider.when('/', { templateUrl: 'view1.html', controller: 'MySimpleCtrl' }); $routeProvider.when('/view2', { templateUrl: 'view2.html', controller: 'MySimpleCtrl' }); $routeProvider.otherwise({ redirectTo: '/' }); }); // Let's add a new controller to MyApp myApp.controller('MySimpleCtrl', function ($scope) { });
Views • view1.html: <h1>View 1</h2> <p><a href="#/view2">To View 2</a></p> • view2.html: <h1>View 2</h2> <p><a href="#/view1">To View 1</a></p>
Working in Local Environment • If you get "cross origin requests are only supported for HTTP" .. • Either – 1) Disable web security in your browser – 2) Use some web server and access files http://.. • To disable web security in chrome – taskkill /F /IM chrome.exe – "C:Program Files (x86)GoogleChromeApplication chrome.exe" --disable-web-security --allow-file-access- from-files
EXERCISE 4: ROUTING
Services • View-‐independentbusiness logic should not be in a controller – Logic should be in a service component • Controllers are view specific, services are app-‐spesific – We can move from view to view and service is still alive • Controller's responsibility is to bind model to view. Model can be fetched from service! – Controller is not responsible for manipulating (create, destroy, update) the data. Use Services instead! • AngularJS has many built-‐inservices, see – http://docs.angularjs.org/api/ng/service – Example: $http
Services ViewCustomers (html fragment) ViewCustomersCtrl $scope Service ModifyCustomers (html fragment) ModifyCustomerCtrl $scope
AngularJS Custom Services using Factory // Let's add a new controller to MyApp. This controller uses Service! myApp.controller('ViewCtrl', function ($scope, CustomerService) { $scope.contacts = CustomerService.contacts; }); // Let's add a new controller to MyApp. This controller uses Service! myApp.controller('ModifyCtrl', function ($scope, CustomerService) { $scope.contacts = CustomerService.contacts; }); // Creating a factory object that contains services for the // controllers. myApp.factory('CustomerService', function() { var factory = {}; factory.contacts = [{name: "Jack", salary: 3000}, {name: "Tina", salary: 5000}, {name: "John", salary: 4000}]; return factory; });
Also Service is instantiated with new – keyword. function can use "this" and the return // Service // Service // value is this. myApp.service('CustomerService', function() { this.contacts = [{name: "Jack", salary: 3000}, {name: {name: "Tina", "John", salary: salary: 5000}, 4000}]; });
AJAX + REST
AJAX • Asynchronous JavaScript + XML – XML not needed, very oden JSON • Send data and retrieve asynchronously from server in background • Group of technologies – HTML, CSS, DOM, XML/JSON, XMLHttpRequest object and JavaScript
$http – example (AJAX) and AngularJS <script type="text/javascript"> var myapp = angular.module("myapp", []); myapp.controller("MyController", function($scope, $http) { $scope.myData = {}; $scope.myData.doClick = function(item, event) { var responsePromise = $http.get("text.txt"); responsePromise.success(function(data, status, headers, config) { $scope.myData.fromServer = data; }); responsePromise.error(function(data, status, headers, config) { alert("AJAX failed!"); }); } } ); </script>
RESTful • Web Service APIs that adhere to REST architectural constrains are called RESTful • Constrains – Base URI, such as http://www.example/resources – Internet media type for data, such as JSON or XML – Standard HTTP methods: GET, POST, PUT, DELETE – Links to reference reference state and related resources
RESTful API HTTP methods (wikipedia)
AJAX + RESTful • The web app can fetch using RESTful data from server • Using AJAX this is done asynchronously in the background • AJAX makes HTTP GET request using url .. – http://example.com/resources/item17 • .. and receives data of item17 in JSON ... • .. which can be displayed in view (web page)
Example: Weather API • Weather information available from wunderground.com – You have to make account and receive a key • To get Helsinki weather in JSON – http://api.wunderground.com/api/your-key/ conditions/q/Helsinki.json
{ "response": { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 } }, "current_observation": { "image": { "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png", "title": "Weather Underground", "link": "http://www.wunderground.com" }, "display_location": { "full": "Helsinki, Finland", "city": "Helsinki", "state": "", "state_name": "Finland", "country": "FI", "country_iso3166": "FI", "zip": "00000", "magic": "1", "wmo": "02974", "latitude": "60.31999969", "longitude": "24.96999931", "elevation": "56.00000000" },
<!DOCTYPE html> <html> <head> <script src="../angular.min.js" type="text/javascript"></script> <title></title> </head> <body data-ng-app="myapp"> <div data-ng-controller="MyController"> <button data-ng-click="myData.doClick(item, $event)">Get Helsinki Weather</button><br /> Data from server: {{myData.fromServer}} </div> <script type="text/javascript"> var myapp = angular.module("myapp", []); myapp.controller("MyController", function($scope, $http) { $scope.myData = {}; $scope.myData.doClick = function(item, event) { var responsePromise = $http.get("http://api.wunderground.com/api/key/conditions/ q/Helsinki.json"); responsePromise.success(function(data, status, headers, config) { $scope.myData.fromServer = "" + data.current_observation.weather + " " + data.current_observation.temp_c + " c"; }); responsePromise.error(function(data, status, headers, config) { alert("AJAX failed!"); }); } } ); </script> </body> </html> This is JSON object!
View after pressing the Button
$resource • Built on top of $http service, $resource is a factory that lets you interact with RESTful backends easily • $resource does not come bundled with main Angular script, separately download – angular-resource.min.js • Your main app should declare dependency on the ngResource module in order to use $resource
Getting Started with $resource • $resource expects classic RESTful backend – http://en.wikipedia.org/wiki/ Representational_state_transfer#Applied_t o_web_services • You can create the backend by whatever technology. Even JavaScript, for example Node.js • We are not concentrating now how to build the backend.
Using $resource on GET // Load ngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, $resource) { $scope.doClick = function() { var title = $scope.movietitle; var searchString = 'http://api.rottentomatoes.com/api/ public/v1.0/movies.json?apikey=key&q=' + title + '&page_limit=5'; var result = $resource(searchString); // {method:'GET'var root = result.get(function() { $scope.movies = root.movies; }); } });
$resource methods • $resource contains convenient methods for – get ('GET') – save ('POST') – query ('GET', isArray:true) – remove ('DELETE') • Calling these will invoke $http (ajax call) with the specified http method (GET, POST, DELETE), destination and parameters
Passing Parameters // Load ngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, $resource) { $scope.doClick = function() { var searchString = 'http://api.rottentomatoes.com/api/public/ v1.0/movies.json?apikey=key&q=:title&page_limit=5'; var result = $resource(searchString); var root = result.get({title: $scope.movietitle}, function() { $scope.movies = root.movies; }); } }); :title -‐> parametrized URL template Giving the parameter from $scope
Using Services // Load ngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, MovieService) { $scope.doClick = function() { var root = MovieService.resource.get({title: $scope.movietitle}, function() { $scope.movies = root.movies; }); }}); restApp.factory('MovieService', function($resource) { factory = {}; factory.resource = $resource('http://api.rottentomatoes...&q=:title&page_limit=5'); return factory; }); Controller responsible for binding Service responsible for the resource
Simple Version // Load ngResource before this var restApp = angular.module('restApp',['ngResource']); MovieService) { $scope.movietitle}, restApp.controller("RestCtrl", function($scope, $scope.doClick = function() { var root = MovieService.get({title: function() { $scope.movies = root.movies; }); } }); restApp.factory('MovieService', function($resource) { return $resource('http://api.rottentomatoes...&q=:title&page_limit=5');; }); Just call get from MovieService Returns the resource
ANIMATIONS AND UNIT TESTING
AngularJS Animations • Include ngAnimate module as dependency • Hook animations for common directives such as ngRepeat, ngSwitch, ngView • Based on CSS classes – If HTML element has class, you can animate it • AngularJS adds special classes to your html-‐ elements
Example Form <body ng-controller="AnimateCtrl"> <button ng-click="add()">Add</button> <button ng-click="remove()">Remove</button></p> <ul> <li ng-repeat="customer in customers">{{customer.name}}</li> </ul> </body> Adds and Removes names
Animation Classes • When adding a new name to the model, ng-‐ repeat knows the item that is either added or deleted • CSS classes are added at runtime to the repeated element (<li>) • When adding new element: – <li class="... ng-enter ng-enter-active">New Name</li> • When removing element – <li class="... ng-leave ng-leave-active">New Name</li>
Directives and CSS Event Starting CSS EndingCSS Directives enter .ng-‐enter .ng-‐enter-‐active ngRepeat, ngInclude, ngIf, ngView leave .ng-‐leave .ng-‐leave-‐active ngRepeat, ngInclude, ngIf, ngView move .ng-‐move .ng-‐move.active ngRepeat
Example CSS /* starting animation */ .ng-enter { -webkit-transition: 1s; transition: 1s; margin-left: 100%; } /* ending animation */ .ng-enter-active { margin-left: 0; } /* starting animation */ .ng-leave { -webkit-transition: 1s; transition: 1s; margin-left: 0; } /* ending animation */ .ng-leave-active { margin-left: 100%; }
Test Driven Design • Write tests firsts, then your code • AngularJS emphasizes modularity, so it can be easy to test your code • Code can be tested using several unit testing frameworks, like QUnit, Jasmine, Mocha ...
QUnit • Download qunit.js and qunit.css • Write a simple HTML page to run the tests • Write the tests
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QUnit Example</title> <link rel="stylesheet" href="qunit- 1.10.0.css"> <script src="qunit-1.10.0.js"></script> </head> <body> <div id="qunit"></div> <script type="text/javascript"> function calculate(a, b) { return a + b; } "Ok!" "Ok!" "OK!" "calculate test", function() { ); ); ); test( ok( calculate(5,5) === 10, ok( calculate(5,0) === 5, ok( calculate(-5,5) === 0, }); </script> </body> </html>
Three Assertions • Basic – ok( boolean [, message]); • If actual == expected – equal( actual, expected [, message]); • if actual === expected – deepEqual( actual, expected [, message)); • Other – http://qunitjs.com/cookbook/#automating- unit-testing
Testing AngularJS Service var myApp = angular.module('myApp', []); // One service myApp.service('MyService', function() { function(a, b) { a + b; this.add = return }; }); /* TESTS */ var injector = angular.injector(['ng', 'myApp']); QUnit.test('MyService', function() { var MyService = injector.get('MyService'); ok(2== MyService.add(1, 1)); });
WRAPPING UP
Web Development Web development is the creation of dynamic web applications. Examples of web applications are social networking sites like Facebook or e-commerce sites like Amazon. Web Development Front-end Development Back-end Development Two broad divisions of web development – • front-end development (also called client-side development) • back-end development (also called server-side development).
Front-End Development Constructing what a user sees when they load a web application – the content, design and how you interact with it. Done with three codes – HTML, CSS and JavaScript.
Back-End Development Back-end development controls what goes on behind the scenes of a web application. A back-end often uses a database to generate the front- end. Back-end scripts are written in many different coding languages and frameworks, such as…  Java  Node.js  Python  PHP  Ruby on Rails  ASP.NET
Latest trends in Web Development  Real time applications  Progressive web applications  Blockchain  Push Notification With Websites  Single-Page Websites  Virtual reality (VR)  Mobile friendly website  Chatbots, AI, and machine learning
Javascript
What is JavaScript ?  Interpreted, client-side, event-based, object oriented scripting language  Used to add dynamic interactivity to your web pages.  Written in plain text, like HTML, XML, Java, PHP In this code  JavaScript is not Java, though both languages look similar when written.  Java is a full featured and comprehensive programming language similar to C or C++, and although JavaScript can interact with Java web applications, the two should not be confused
JavaScript - Syntax  JS can be implemented using JavaScript statements that are placed within the <script>... </script>.  Script tag takes two important attributes − 1) Language - Specifies what scripting language you are using 2) Type - To indicate the scripting language in use and its value should be set to "text/javascript".
Advantages of JavaScript  Less server interaction  Immediate feedback to the visitors  Increased interactivity  Richer interfaces  JavaScript is an easy language to learn  Easy to debug and test  Platform independent  Event-Based Programming language
Why javascript is the future of programming?
Why javascript is the future of programming?
 GitHub Octoverse Most popular languages on GitHub by opened pull requests (displayed in millions). Career Scope of JS  TIOBE Rating: (January 2018) The TIOBE rating is an indicator of the popularity of programming languages.
Career Scope of JS  PYPL PopularitY of Programming Language (April 2018) The PYPL PopularitY of Programming Language Index is created by analyzing how often language tutorials are searched on Google.  Stack Overflow Developer Survey 2018
Angular JS
What is AngularJS AngularJS is a client side JavaScript MVC framework to develop a dynamic web application. AngularJS was originally started as a project in Google but now, it is open source framework.
Why AngularJS  Structure, Quality and Organization  Lightweight ( < 36KB compressed and minified)  Free  Separation of concern  Modularity  Extensibility & Maintainability  Reusable Components
Features of AngularJS  Two-way Data Binding – Model as single source of truth  Directives – Extend HTML  MVC  Dependency Injection  Testing  Deep Linking (Map URL to route Definition)  Server-Side Communication
MVC Controller Model View JS Classes DOM JS Objects
Other Javascript Frameworks  BackboneJS  EmberJS
Expressions  AngularJS expressions can be written inside double braces: {{ expression }}.  AngularJS expressions can also be written inside a directive: ng-bind="expression".  Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
Modules  An AngularJS module defines an application.  The module is a container for the different parts of an application.  The module is a container for the application controllers.  Controllers always belong to a module.
Controllers  AngularJS controllers control the data of AngularJS applications.  AngularJS controllers are regular JavaScript Objects.  The ng-controller directive defines the application controller
Services  In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application.  AngularJS has about 30 built-in services. One of them is the $location service.  The $location service has methods which return information about the location of the current web page
Filters  currency Format a number to a currency format.  date Format a date to a specified format.  filter Select a subset of items from an array.  json Format an object to a JSON string.  limitTo Limits an array/string, into a specified number of elements/characters.  lowercase Format a string to lower case.  number Format a number to a string.  orderBy Orders an array by an expression.  uppercase Format a string to upper case.
Scope  The scope is the binding part between the HTML (view) and the JavaScript (controller).  The scope is an object with the available properties and methods.  The scope is available for both the view and the controller.
Node JS
What is NodeJs  A JavaScript runtime environment running Google Chrome’s V8 engine  A server-side solution for JS  Compiles JS, making it really fast  Runs over the command line  Designed for high concurrency  Without threads or new processes  Never blocks, not even for I/O  Uses the CommonJS framework  Making it a little closer to a real OO language
Node JS vs Apache • It is fast • It can handle tons of concurrent requests • It is written in JavaScript (which means you can use the same code server side and client side) Platform Number of request per second PHP ( via Apache) 3187,27 Static ( via Apache ) 2966,51 Node.js 5569,30
Creating Node.js Application Execute the main.js to start the server as below
REPL Terminal  REPL stands for Read Eval Print Loop  Node comes bundled with a REPL environment. It performs the following tasks −  Read − Reads user's input, parses the input into JavaScript data- structure, and stores in memory.  Eval − Takes and evaluates the data structure.  Print − Prints the result.  Loop − Loops the above command until the user presses ctrl-c twice.
Node Package Manager (NPM)  Node Package Manager (NPM) provides two main functionalities −  Online repositories for node.js packages/modules which are searchable on search.nodejs.org  Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.  Installing Modules using NPM  npm install <Module Name>
Wrapping UP • AngularJS is a modular JavaScript SPA framework • Lot of great features, but learning curve can be hard • Great for CRUD (create, read, update, delete) apps, but not suitable for every type of apps • Works very well with some JS libraries (JQuery)
Superset of JavaScript Modular Scalable Application Structure Strong Typing Tooling Support EcmaScript 6 Standards Why TypeScript?
What is TypeScript? Strongly Typed Classes Interfaces Generics Modules Type Definitions Compiles to JavaScript EcmaScript 6 Features

Angular jS Introduction by Google

  • 2.
    • Objectives: Basic WebApplication Model Web Development Frameworks/Languages • Resources: Web Frameworks Popular Frameworks 10 Things to Know Angular React Knockout • Videos: Rest Postman Chrome Developer Tools LECTURE 32: INTRO TO WEB DEVELOPMENT
  • 3.
    Principles of WebDesign Availability Performance Reliability Scalability Manageability Cost
  • 4.
    Core Components ofWeb Applications UI (Front End (DOM, Framework)) Request Layer (Web API) Back End (Database, Logic) Internet Browser Media Cache API Front End JSON Database Logic ClientServer
  • 5.
  • 6.
    Front End Languages HTML/CSS Javascript Java(applets) What is the most popular? Answer: Javascript/HTML/CSS is the only real option for front-end native languages and is basically the standard. But there are many variations on JavaScript that are used.
  • 7.
    DOM (Document ObjectModel) Document Object Model makes every addressable item in a web application an Object that can be manipulated for color, transparency, position, sound and behaviors. Every HTML Tag is a DOM object
  • 8.
    DOM (Document ObjectModel) DOM CSS HTML JavaScript
  • 9.
    What is aFramework? Software Framework designed to reduce overhead in web development Types of Framework Architectures Model-View-Controller (MVC) Push vs Pull Based Most MVC Frameworks user push-based architecture “action based” (Django, Ruby on Rails, Symfony, Stripes) Pull-based or “component based” (Lift, Angular2, React) Three Tier Organization Client (Usually the browser running HTML/Javascipt/CSS) Application (Running the Business Logic) Database (Data Storage) Types of Frameworks Server Side: Django, Ruby on Rails Client Side: Angular, React, Vue
  • 10.
  • 11.
  • 12.
    MVC (Model ViewController) A Web Application Development Framework Model (M): Where the data for the DOM is stored and handled) This is where the backend connects View (V): Think of this like a Page which is a single DOM Where changes to the page are rendered and displayed Control (C): This handles user input and interactions Buttons Forms General Interface
  • 13.
  • 14.
  • 15.
    What is aBackend? All of the awesome that runs your application. Web API Connection layer between the frontend and backend Connected through API calls (POST, GET, PUT, etc. ) Transmit Content from the Backend to the Frontend commonly in JSON Blobs Service Architecture that drives everything (Where all the logic is)
  • 16.
    What is aWebAPI? The intermediate layer between front end and back-end systems A “must have” if your APIs will be consumed by third-party services Attention to details: How consumable is the API (signature, content negotiation)? Does it comply with standards (response codes, etc.)? Is it secure? How do you handle multiple versions? Is it truly RESTful?
  • 17.
    Representational State Transfer(REST) Client-server Stateless Resource-based (vs. remote procedure call) HTTP methods (GET, POST, PUT, DELETE) Side Effects It’s a style, not a standard Don’t hate on HATEOAS
  • 18.
    WebAPI Terms GET –“read” POST – “insert” (collection) PUT – “replace” DELETE – “remove” PATCH – “update” Custom (proceed with caution)
  • 19.
    Web Status Codes 200– OK – things are great (return the item) 201 Created – after POST (HATEOAS – return location) 204 No Content (i.e. successful DELETE) 400 – Bad Request (validation error, missing parms, etc.) 401 – Unauthorized – Who are you? 403 – Forbidden – No soup for you 404 – Not Found
  • 20.
    What is Angular MVCStructure Framework Single Page Application (SPA) Client Side Template Testing
  • 21.
    Building Blocks Directives Component –Templates (HTML), Styles (CSS), & Logic (JavaScript) Attribute – Styling HTML Structural – Manipulating HTML Data Flow Interpolation – Variable Printing in Templates Event Binding – Trigger Events 2-Way Binding – Variables updated in real time Providers Services Reusable Logic Data Storing and Manipulation Libraries
  • 22.
    Component Directives "…reusable buildingblocks for an application" Components have: HTML CSS JavaScript
  • 23.
    JavaScript – 1995 Netscape ECMAScriptStandard – June 1997 Garret coins Ajax - 2005 Prototype, Dojo, jQuery –ECMAScript 5 – 20092005/2006 JSON Support History
  • 24.
    AngularJS – 2009 React– 2011 Facebook NewsFeed React – 2013 Open Sourced AngularJS 2.0 – Announced Sept 2014 Breaking changes ECMAScript 6 – June 2016 History
  • 25.
    From the finefolks at Google AngularJS 1.x – Google JavaScript library for development AngularJS 2.x – Called Angular Angular is a Framework Angular is opinionated Angular has code in your markup Angular is HTML centric AngularJS
  • 26.
    Angular is aFramework. React is a Library Not The Same
  • 27.
    Mobile First Standards focused Performance VirtualDom Web Components Angular – Why
  • 28.
    import { Component} from 'angular2/core'; @Component({ selector: 'foo-Div', templateUrl: 'app/foo.html', styleUrls: [ 'app/foo.css' ] }) export class Foo { public message = 'Foo!'; } Component Angular
  • 29.
    Angular separate HTMLfile React HTML is in render method •JSX allows for HTML like Angular has one way and two way data binding •{{element.name}} •<input type="text" [(ngModel)]="inputFieldName" id="id1" /> React is stateless, no two way binding •This.state.inputFieldName Templates and Databinding
  • 30.
    Rise of theResponsive Single Page App
  • 31.
    Responsive • Unified across experiences •Can be embedded as mobile app • Better deployment and & maintanence • Mobile users need to get access to everything Image: http://coenraets.org/blog/wp-‐content/uploads/2011/10/directory11.png
  • 32.
    Single-‐pageApplications (SPA) • Webapp that fits on a single web page – Fluid UX, like desktop app – Examples like Gmail, Google maps • Html page contains mini-‐views(HTML Fragments) that can be loaded in the background • No reloading of the page, • Requires handling of browser history, navigation and bookmarks
  • 33.
    JavaScript • SPAs areimplemented using JavaScript and HTML
  • 34.
    Challenges in SPA •DOM Manipulation – How to manipulate the view efficiently? • History – What happens when pressing back button? • Routing – Readable URLs? • Data Binding – How bind data from model to view? • View Loading – How to load the view? • Lot of coding! You could use a framework instead ...
  • 35.
    Single-page Application Single pageapps typically have “application like” interaction dynamic data loading from the server-side API fluid transitions between page states more JavaScript than actual HTML They typically do not have support for crawlers (not for sites relying on search traffic) support for legacy browsers (IE7 or older, dumbphone browsers)
  • 36.
    SPAs Are GoodFor … • “App-like user experience” • Binding to your own (or 3rd party) RESTful API • Replacement for Flash or Java in your web pages • Hybrid (native) HTML5 applications • Mobile version of your web site The SPA sweet spot is likely not on web sites, but on content-rich cross-platform mobile apps
  • 37.
    PJAX Pjax is atechnique that allows you to progressively enhance normal links on a page so that clicks result in the linked content being loaded via Ajax and the URL being updated using HTML5 pushState, avoiding a full page load. In browsers that don't support pushState or that have JavaScript disabled, link clicks will result in a normal full page load. The Pjax Utility makes it easy to add this functionality to existing pages.
  • 38.
    SPAs and OtherWeb App Architectures Server-side Server-side + AJAX PJAX SPA What Server round-trip on every app state change Render initial page on server, state changes on the client Render initial page on server, state changes on server, inject into DOM on client-side Serve static page skeleton from server; render every change on client-side How UI code on server; links & form posting UI code on both ends; AJAX calls, ugly server API UI code on server, client to inject HTTP, server API if you like UI code on client, server API Ease of development UX & responsiveness Robots & old browsers Who’s using it? Amazon, Wikipedia; banks, media sites etc. Facebook?; widgets, search Twitter, Basecamp, GitHub Google+, Gmail, FT; mobile sites, startups
  • 39.
    Angular JS • SinglePage App Framework for JavaScript • Implements client-‐sideMVC pattern – Separation of presentation from business logic and presentation state • No direct DOM manipulation, less code • Support for all major browsers • Supported by Google • Large and fast growing community
  • 40.
    AngularJS – MainConcepts • Templates • Directives • Expressions • Data binding • Scope • Controllers • Modules • Filters • Services • Routing
  • 41.
    Anatomy of aBackbone SPA • Application as a ‘singleton’ reference holder • Router handles the navigation and toggles between views • Models synchronize with Server API • Bulk of the code in views • All HTML in templates
  • 42.
  • 43.
    SPA Client-Server Communication •HTML and all the assets are loaded in first request • Additional data is fetched over XMLHTTPRequest • If you want to go real-time, WebSockets (socket.io) can help you
  • 44.
  • 45.
  • 46.
    Basic Concepts • 1)Templates – HTML with additional markup, directives, expressions, filters ... • 2) Directives – Extend HTML using ng-app, ng-bind, ng-model • 3) Filters – Filter the output: filter, orderBy, uppercase • 4) Data Binding – Bind model to view using expressions {{ }}
  • 47.
    First Example –Template <!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angu lar.min.js"></script> </head> <body> <div ng-app> <!-- store the value of input field into a variable name --> <p>Name: <input type="text" ng-model="name"></p> <!-- display the variable name inside (innerHTML) of p --> <p ng-bind="name"></p> </div> </body> </html> Template
  • 48.
    2) Directives • Directivesapply special behavior to attributes or elements in HTML – Attach behaviour, transform the DOM • Some directives – ng-app • Initializes the app – ng-model • Stores/updates the value of the input field into a variable – ng-bind • Replace the text content of the specified HTML with the value of given expression
  • 49.
    About Naming • AngularJSHTML Compiler supports multiple formats – ng-bind • Recommended Format – data-ng-bind • Recommended Format to support HTML validation – ng_bind, ng:bind, x-ng-bind • Legacy, don't use
  • 50.
    Lot of Builtin Directives • ngApp • ngClick • ngController • ngModel • ngRepeat • ngSubmit • ngDblClick • ngMouseEnter • ngMouseMove • ngMouseLeave • ngKeyDown • ngForm
  • 51.
    2) Expressions • Angularexpressions are JavaScript-‐likecode snippets that are usually placed in bindings – {{ expression }}. • Valid Expressions – {{ 1 + 2 }} – {{ a + b }} – {{ items[index] }} • Control flow (loops, if) are not supported! • You can use filters to format or filter data
  • 52.
    Example <!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8"/> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">< /script> </head> <body> <div ng-app> <p>Number 1: <input type="number" ng-model="number1"></p> <p>Number 2: <input type="number" ng-model="number2"></p> <!-- expression --> <p>{{ number1 + number2 }}</p> </div> </body> </html> Directive Expression Directive
  • 53.
    ng-‐initand ng-‐repeat directives <!DOCTYPEhtml> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min .js"></script> </head> <body> <div data-ng-init="names = ['Jack', 'John', 'Tina']"> <h1>Cool loop!</h1> <ul> <li data-ng-repeat="name in names">{{ name }}</li> </ul> </div> </body> </html>
  • 54.
    3) Filter • Withfilter, you can format or filter the output • Formatting – currency, number, date, lowercase, uppercase • Filtering – filter, limitTo • Other – orderBy, json
  • 55.
    Using Filters -‐Example <!DOCTYPEhtml> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">< /script> </head> <body> <div data-ng-init="customers = [{name:’tina'}, {name:’jack'}]"> <h1>Cool loop!</h1> <ul> <li data-ng-repeat="customer in customers | orderBy:'name'"> {{ customer.name | uppercase }}</li> </ul> </div> </body> </html> Filter Filter
  • 56.
    Using Filters -‐Example <!DOCTYPEhtml> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div data-ng-init= "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]"> <h1>Customers</h1> <ul> <li data-ng-repeat="customer in customers | orderBy:'name' | filter:'john'">{{ customer.name | uppercase }}</li> </ul> </div> </body> </html>
  • 57.
    Using Filters –User Input Filters the Data <!DOCTYPE html> <html data-ng-app=""> <head> <title>Title</title> <meta charset="UTF-8" /> <style media="screen"></style> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">< /script> </head> <body> <div data-ng-init= "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]"> <h1>Customers</h1> <input type="text" data-ng-model="userInput" /> <ul> <li data-ng-repeat="customer in customers | orderBy:'name' | filter:userInput">{{ customer.name | uppercase }}</li> </ul> </div> </body> </html>
  • 58.
  • 59.
  • 60.
    Model – View-‐Controllers • Controllers provide the logic behind your app. – So use controller when you need logic behind your UI • AngularJS apps are controller by controllers • Use ng-‐controllerto define the controller • Controller is a JavaScript Object, created by standard JS object constructor
  • 61.
    Model – View-‐Controllers a controller is a JavaScript function ○ It contains data ○ It specifies the behavior ○ It should contain only the business logic needed for a single view.
  • 62.
    View, Controller andScope View (html fragment) Controller$scope $scope is an object that can be used to communicate between View and Controller
  • 63.
  • 64.
    <!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8"/> <style media="screen"></style> <script src="https://ajax.googleapis.com/ ajax/libs/angularjs/1.4.8/angular.min.js"> </script> </head> <body> <div data-ng-app="myApp" data-ng-controller="NumberCtrl"> <p>Number: <input type="number" ng-model="number"></p> <p>Number = {{ number }}</p> <button ng-click="showNumber()">Show Number</button> </div> <script> var app = angular.module('myApp', []); app.controller('NumberCtrl', function($scope) { $scope.number = 1; $scope.showNumber = function(){ window.alert( "your number= " + $scope.number ); }; }); </script> </body> </html>
  • 65.
    Modules • Module isan reusable container for different features of your app – Controllers, services, filters, directives... • If you have a lot of controllers, you are polluting JS namespace • Modules can be loaded in any order • We can build our own filters and directives!
  • 66.
    When to useControllers • Use controllers – set up the initial state of $scope object – add behavior to the $scope object • Do not – Manipulate DOM (use databinding, directives) – Format input (use form controls) – Filter output (use filters) – Share code or state (use services)
  • 67.
    App Explained • Appruns inside ng-app (div) • AngularJS will invoke the constructor with a $scope – object • $scope is an object that links controller to the view
  • 68.
  • 69.
    Example: Own Filter //declare a module var myAppModule = angular.module('myApp', []); filter // configure the module. // in this example we will create a greeting myAppModule.filter('greet', function() { return function(name) { ' + name + '!';return 'Hello, }; });
  • 70.
    HTML using theFilter <div ng-app="myApp"> <div> {{ 'World' | greet }} </div> </div>
  • 71.
    Template for Controllers //Create new module 'myApp' using angular.module method. // The module is not dependent on any other module var myModule = angular.module('myModule', []); myModule.controller('MyCtrl', function ($scope) { // Your controller code here! });
  • 72.
    Creating a Controllerin Module var myModule = angular.module('myModule', []); myModule.controller('MyCtrl', function ($scope) { var model = { "firstname": "Jack", "lastname": "Smith" }; $scope.model = model; $scope.click = function() { alert($scope.model.firstname); }; });
  • 73.
    <!DOCTYPE html> <html> <head> <title>Title</title> <meta charset="UTF-8"/> <style media="screen"></style> <script <script src="../angular.min.js"></script> src="mymodule.js"></script> </head> <body> <div ng-app="myModule" <div ng-controller="MyCtrl"> <p>Firstname: <input type="text" ng-model="model.firstname"></p> <p>Lastname: <input type="text" ng-model="model.lastname"></p> <p>{{model.firstname + " " + model.lastname}}</p> <button ng-click="click()">Show Number</button> </div> </div> </body> </html> This is now the model object from MyCtrl. Model object is shared with view and controller
  • 74.
  • 75.
    Routing • Since weare building a SPA app, everything happens in one page – How should back-‐button work? – How should linking between "pages" work? – How about URLs? • Routing comes to rescue!
  • 76.
    <html data-ng-app="myApp"> <head> <title>Demonstration ofRouting - index</title> <meta charset="UTF-8" /> src="../angular.min.js" type="text/javascript"></script> src="angular-route.min.js" type="text/javascript"></script> src="myapp.js" type="text/javascript"> <script <script <script </script> </head> <body> <div data-ng-view=""></div> </body> </html> The content of this will change dynamically We will have to load additional module
  • 77.
    // This moduleis dependent on ngRoute. Load ngRoute // before this. var myApp = angular.module('myApp', ['ngRoute']); views. // Configure routing. myApp.config(function($routeProvider) { // Usually we have different controllers for different // In this demonstration, the controller does nothing. $routeProvider.when('/', { templateUrl: 'view1.html', controller: 'MySimpleCtrl' }); $routeProvider.when('/view2', { templateUrl: 'view2.html', controller: 'MySimpleCtrl' }); $routeProvider.otherwise({ redirectTo: '/' }); }); // Let's add a new controller to MyApp myApp.controller('MySimpleCtrl', function ($scope) { });
  • 78.
    Views • view1.html: <h1>View 1</h2> <p><ahref="#/view2">To View 2</a></p> • view2.html: <h1>View 2</h2> <p><a href="#/view1">To View 1</a></p>
  • 79.
    Working in LocalEnvironment • If you get "cross origin requests are only supported for HTTP" .. • Either – 1) Disable web security in your browser – 2) Use some web server and access files http://.. • To disable web security in chrome – taskkill /F /IM chrome.exe – "C:Program Files (x86)GoogleChromeApplication chrome.exe" --disable-web-security --allow-file-access- from-files
  • 80.
  • 81.
    Services • View-‐independentbusiness logicshould not be in a controller – Logic should be in a service component • Controllers are view specific, services are app-‐spesific – We can move from view to view and service is still alive • Controller's responsibility is to bind model to view. Model can be fetched from service! – Controller is not responsible for manipulating (create, destroy, update) the data. Use Services instead! • AngularJS has many built-‐inservices, see – http://docs.angularjs.org/api/ng/service – Example: $http
  • 82.
  • 83.
    AngularJS Custom Servicesusing Factory // Let's add a new controller to MyApp. This controller uses Service! myApp.controller('ViewCtrl', function ($scope, CustomerService) { $scope.contacts = CustomerService.contacts; }); // Let's add a new controller to MyApp. This controller uses Service! myApp.controller('ModifyCtrl', function ($scope, CustomerService) { $scope.contacts = CustomerService.contacts; }); // Creating a factory object that contains services for the // controllers. myApp.factory('CustomerService', function() { var factory = {}; factory.contacts = [{name: "Jack", salary: 3000}, {name: "Tina", salary: 5000}, {name: "John", salary: 4000}]; return factory; });
  • 84.
    Also Service is instantiatedwith new – keyword. function can use "this" and the return // Service // Service // value is this. myApp.service('CustomerService', function() { this.contacts = [{name: "Jack", salary: 3000}, {name: {name: "Tina", "John", salary: salary: 5000}, 4000}]; });
  • 85.
  • 86.
    AJAX • Asynchronous JavaScript+ XML – XML not needed, very oden JSON • Send data and retrieve asynchronously from server in background • Group of technologies – HTML, CSS, DOM, XML/JSON, XMLHttpRequest object and JavaScript
  • 87.
    $http – example(AJAX) and AngularJS <script type="text/javascript"> var myapp = angular.module("myapp", []); myapp.controller("MyController", function($scope, $http) { $scope.myData = {}; $scope.myData.doClick = function(item, event) { var responsePromise = $http.get("text.txt"); responsePromise.success(function(data, status, headers, config) { $scope.myData.fromServer = data; }); responsePromise.error(function(data, status, headers, config) { alert("AJAX failed!"); }); } } ); </script>
  • 88.
    RESTful • Web ServiceAPIs that adhere to REST architectural constrains are called RESTful • Constrains – Base URI, such as http://www.example/resources – Internet media type for data, such as JSON or XML – Standard HTTP methods: GET, POST, PUT, DELETE – Links to reference reference state and related resources
  • 89.
    RESTful API HTTPmethods (wikipedia)
  • 90.
    AJAX + RESTful •The web app can fetch using RESTful data from server • Using AJAX this is done asynchronously in the background • AJAX makes HTTP GET request using url .. – http://example.com/resources/item17 • .. and receives data of item17 in JSON ... • .. which can be displayed in view (web page)
  • 91.
    Example: Weather API •Weather information available from wunderground.com – You have to make account and receive a key • To get Helsinki weather in JSON – http://api.wunderground.com/api/your-key/ conditions/q/Helsinki.json
  • 92.
    { "response": { "version": "0.1", "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 } }, "current_observation": { "image": { "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png", "title": "Weather Underground", "link": "http://www.wunderground.com" }, "display_location": { "full": "Helsinki, Finland", "city": "Helsinki", "state": "", "state_name": "Finland", "country": "FI", "country_iso3166": "FI", "zip": "00000", "magic": "1", "wmo": "02974", "latitude": "60.31999969", "longitude": "24.96999931", "elevation": "56.00000000" },
  • 93.
    <!DOCTYPE html> <html> <head> <script src="../angular.min.js"type="text/javascript"></script> <title></title> </head> <body data-ng-app="myapp"> <div data-ng-controller="MyController"> <button data-ng-click="myData.doClick(item, $event)">Get Helsinki Weather</button><br /> Data from server: {{myData.fromServer}} </div> <script type="text/javascript"> var myapp = angular.module("myapp", []); myapp.controller("MyController", function($scope, $http) { $scope.myData = {}; $scope.myData.doClick = function(item, event) { var responsePromise = $http.get("http://api.wunderground.com/api/key/conditions/ q/Helsinki.json"); responsePromise.success(function(data, status, headers, config) { $scope.myData.fromServer = "" + data.current_observation.weather + " " + data.current_observation.temp_c + " c"; }); responsePromise.error(function(data, status, headers, config) { alert("AJAX failed!"); }); } } ); </script> </body> </html> This is JSON object!
  • 94.
  • 95.
    $resource • Built ontop of $http service, $resource is a factory that lets you interact with RESTful backends easily • $resource does not come bundled with main Angular script, separately download – angular-resource.min.js • Your main app should declare dependency on the ngResource module in order to use $resource
  • 96.
    Getting Started with$resource • $resource expects classic RESTful backend – http://en.wikipedia.org/wiki/ Representational_state_transfer#Applied_t o_web_services • You can create the backend by whatever technology. Even JavaScript, for example Node.js • We are not concentrating now how to build the backend.
  • 97.
    Using $resource onGET // Load ngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, $resource) { $scope.doClick = function() { var title = $scope.movietitle; var searchString = 'http://api.rottentomatoes.com/api/ public/v1.0/movies.json?apikey=key&q=' + title + '&page_limit=5'; var result = $resource(searchString); // {method:'GET'var root = result.get(function() { $scope.movies = root.movies; }); } });
  • 98.
    $resource methods • $resourcecontains convenient methods for – get ('GET') – save ('POST') – query ('GET', isArray:true) – remove ('DELETE') • Calling these will invoke $http (ajax call) with the specified http method (GET, POST, DELETE), destination and parameters
  • 99.
    Passing Parameters // LoadngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, $resource) { $scope.doClick = function() { var searchString = 'http://api.rottentomatoes.com/api/public/ v1.0/movies.json?apikey=key&q=:title&page_limit=5'; var result = $resource(searchString); var root = result.get({title: $scope.movietitle}, function() { $scope.movies = root.movies; }); } }); :title -‐> parametrized URL template Giving the parameter from $scope
  • 100.
    Using Services // LoadngResource before this var restApp = angular.module('restApp',['ngResource']); restApp.controller("RestCtrl", function($scope, MovieService) { $scope.doClick = function() { var root = MovieService.resource.get({title: $scope.movietitle}, function() { $scope.movies = root.movies; }); }}); restApp.factory('MovieService', function($resource) { factory = {}; factory.resource = $resource('http://api.rottentomatoes...&q=:title&page_limit=5'); return factory; }); Controller responsible for binding Service responsible for the resource
  • 101.
    Simple Version // LoadngResource before this var restApp = angular.module('restApp',['ngResource']); MovieService) { $scope.movietitle}, restApp.controller("RestCtrl", function($scope, $scope.doClick = function() { var root = MovieService.get({title: function() { $scope.movies = root.movies; }); } }); restApp.factory('MovieService', function($resource) { return $resource('http://api.rottentomatoes...&q=:title&page_limit=5');; }); Just call get from MovieService Returns the resource
  • 102.
  • 103.
    AngularJS Animations • IncludengAnimate module as dependency • Hook animations for common directives such as ngRepeat, ngSwitch, ngView • Based on CSS classes – If HTML element has class, you can animate it • AngularJS adds special classes to your html-‐ elements
  • 104.
    Example Form <body ng-controller="AnimateCtrl"> <buttonng-click="add()">Add</button> <button ng-click="remove()">Remove</button></p> <ul> <li ng-repeat="customer in customers">{{customer.name}}</li> </ul> </body> Adds and Removes names
  • 105.
    Animation Classes • Whenadding a new name to the model, ng-‐ repeat knows the item that is either added or deleted • CSS classes are added at runtime to the repeated element (<li>) • When adding new element: – <li class="... ng-enter ng-enter-active">New Name</li> • When removing element – <li class="... ng-leave ng-leave-active">New Name</li>
  • 106.
    Directives and CSS EventStarting CSS EndingCSS Directives enter .ng-‐enter .ng-‐enter-‐active ngRepeat, ngInclude, ngIf, ngView leave .ng-‐leave .ng-‐leave-‐active ngRepeat, ngInclude, ngIf, ngView move .ng-‐move .ng-‐move.active ngRepeat
  • 107.
    Example CSS /* startinganimation */ .ng-enter { -webkit-transition: 1s; transition: 1s; margin-left: 100%; } /* ending animation */ .ng-enter-active { margin-left: 0; } /* starting animation */ .ng-leave { -webkit-transition: 1s; transition: 1s; margin-left: 0; } /* ending animation */ .ng-leave-active { margin-left: 100%; }
  • 108.
    Test Driven Design •Write tests firsts, then your code • AngularJS emphasizes modularity, so it can be easy to test your code • Code can be tested using several unit testing frameworks, like QUnit, Jasmine, Mocha ...
  • 109.
    QUnit • Download qunit.jsand qunit.css • Write a simple HTML page to run the tests • Write the tests
  • 110.
    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QUnitExample</title> <link rel="stylesheet" href="qunit- 1.10.0.css"> <script src="qunit-1.10.0.js"></script> </head> <body> <div id="qunit"></div> <script type="text/javascript"> function calculate(a, b) { return a + b; } "Ok!" "Ok!" "OK!" "calculate test", function() { ); ); ); test( ok( calculate(5,5) === 10, ok( calculate(5,0) === 5, ok( calculate(-5,5) === 0, }); </script> </body> </html>
  • 111.
    Three Assertions • Basic –ok( boolean [, message]); • If actual == expected – equal( actual, expected [, message]); • if actual === expected – deepEqual( actual, expected [, message)); • Other – http://qunitjs.com/cookbook/#automating- unit-testing
  • 112.
    Testing AngularJS Service varmyApp = angular.module('myApp', []); // One service myApp.service('MyService', function() { function(a, b) { a + b; this.add = return }; }); /* TESTS */ var injector = angular.injector(['ng', 'myApp']); QUnit.test('MyService', function() { var MyService = injector.get('MyService'); ok(2== MyService.add(1, 1)); });
  • 113.
  • 114.
    Web Development Web developmentis the creation of dynamic web applications. Examples of web applications are social networking sites like Facebook or e-commerce sites like Amazon. Web Development Front-end Development Back-end Development Two broad divisions of web development – • front-end development (also called client-side development) • back-end development (also called server-side development).
  • 115.
    Front-End Development Constructing whata user sees when they load a web application – the content, design and how you interact with it. Done with three codes – HTML, CSS and JavaScript.
  • 116.
    Back-End Development Back-end developmentcontrols what goes on behind the scenes of a web application. A back-end often uses a database to generate the front- end. Back-end scripts are written in many different coding languages and frameworks, such as…  Java  Node.js  Python  PHP  Ruby on Rails  ASP.NET
  • 117.
    Latest trends inWeb Development  Real time applications  Progressive web applications  Blockchain  Push Notification With Websites  Single-Page Websites  Virtual reality (VR)  Mobile friendly website  Chatbots, AI, and machine learning
  • 118.
  • 119.
    What is JavaScript?  Interpreted, client-side, event-based, object oriented scripting language  Used to add dynamic interactivity to your web pages.  Written in plain text, like HTML, XML, Java, PHP In this code  JavaScript is not Java, though both languages look similar when written.  Java is a full featured and comprehensive programming language similar to C or C++, and although JavaScript can interact with Java web applications, the two should not be confused
  • 120.
    JavaScript - Syntax JS can be implemented using JavaScript statements that are placed within the <script>... </script>.  Script tag takes two important attributes − 1) Language - Specifies what scripting language you are using 2) Type - To indicate the scripting language in use and its value should be set to "text/javascript".
  • 121.
    Advantages of JavaScript Less server interaction  Immediate feedback to the visitors  Increased interactivity  Richer interfaces  JavaScript is an easy language to learn  Easy to debug and test  Platform independent  Event-Based Programming language
  • 122.
    Why javascript isthe future of programming?
  • 123.
    Why javascript isthe future of programming?
  • 124.
     GitHub Octoverse Mostpopular languages on GitHub by opened pull requests (displayed in millions). Career Scope of JS  TIOBE Rating: (January 2018) The TIOBE rating is an indicator of the popularity of programming languages.
  • 125.
    Career Scope ofJS  PYPL PopularitY of Programming Language (April 2018) The PYPL PopularitY of Programming Language Index is created by analyzing how often language tutorials are searched on Google.  Stack Overflow Developer Survey 2018
  • 126.
  • 127.
    What is AngularJS AngularJSis a client side JavaScript MVC framework to develop a dynamic web application. AngularJS was originally started as a project in Google but now, it is open source framework.
  • 128.
    Why AngularJS  Structure,Quality and Organization  Lightweight ( < 36KB compressed and minified)  Free  Separation of concern  Modularity  Extensibility & Maintainability  Reusable Components
  • 129.
    Features of AngularJS Two-way Data Binding – Model as single source of truth  Directives – Extend HTML  MVC  Dependency Injection  Testing  Deep Linking (Map URL to route Definition)  Server-Side Communication
  • 130.
  • 131.
    Other Javascript Frameworks BackboneJS  EmberJS
  • 132.
    Expressions  AngularJS expressionscan be written inside double braces: {{ expression }}.  AngularJS expressions can also be written inside a directive: ng-bind="expression".  Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
  • 133.
    Modules  An AngularJSmodule defines an application.  The module is a container for the different parts of an application.  The module is a container for the application controllers.  Controllers always belong to a module.
  • 134.
    Controllers  AngularJS controllerscontrol the data of AngularJS applications.  AngularJS controllers are regular JavaScript Objects.  The ng-controller directive defines the application controller
  • 135.
    Services  In AngularJS,a service is a function, or object, that is available for, and limited to, your AngularJS application.  AngularJS has about 30 built-in services. One of them is the $location service.  The $location service has methods which return information about the location of the current web page
  • 136.
    Filters  currency Formata number to a currency format.  date Format a date to a specified format.  filter Select a subset of items from an array.  json Format an object to a JSON string.  limitTo Limits an array/string, into a specified number of elements/characters.  lowercase Format a string to lower case.  number Format a number to a string.  orderBy Orders an array by an expression.  uppercase Format a string to upper case.
  • 137.
    Scope  The scopeis the binding part between the HTML (view) and the JavaScript (controller).  The scope is an object with the available properties and methods.  The scope is available for both the view and the controller.
  • 138.
  • 139.
    What is NodeJs A JavaScript runtime environment running Google Chrome’s V8 engine  A server-side solution for JS  Compiles JS, making it really fast  Runs over the command line  Designed for high concurrency  Without threads or new processes  Never blocks, not even for I/O  Uses the CommonJS framework  Making it a little closer to a real OO language
  • 140.
    Node JS vsApache • It is fast • It can handle tons of concurrent requests • It is written in JavaScript (which means you can use the same code server side and client side) Platform Number of request per second PHP ( via Apache) 3187,27 Static ( via Apache ) 2966,51 Node.js 5569,30
  • 141.
    Creating Node.js Application Executethe main.js to start the server as below
  • 142.
    REPL Terminal  REPLstands for Read Eval Print Loop  Node comes bundled with a REPL environment. It performs the following tasks −  Read − Reads user's input, parses the input into JavaScript data- structure, and stores in memory.  Eval − Takes and evaluates the data structure.  Print − Prints the result.  Loop − Loops the above command until the user presses ctrl-c twice.
  • 143.
    Node Package Manager(NPM)  Node Package Manager (NPM) provides two main functionalities −  Online repositories for node.js packages/modules which are searchable on search.nodejs.org  Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.  Installing Modules using NPM  npm install <Module Name>
  • 144.
    Wrapping UP • AngularJSis a modular JavaScript SPA framework • Lot of great features, but learning curve can be hard • Great for CRUD (create, read, update, delete) apps, but not suitable for every type of apps • Works very well with some JS libraries (JQuery)
  • 146.
    Superset of JavaScript Modular ScalableApplication Structure Strong Typing Tooling Support EcmaScript 6 Standards Why TypeScript?
  • 147.
    What is TypeScript? Strongly Typed ClassesInterfaces Generics Modules Type Definitions Compiles to JavaScript EcmaScript 6 Features

Editor's Notes

  • #4 Availability: The uptime of a website is absolutely critical to the reputation and functionality of many companies. For some of the larger online retail sites, being unavailable for even minutes can result in thousands or millions of dollars in lost revenue, so designing their systems to be constantly available and resilient to failure is both a fundamental business and a technology requirement. High availability in distributed systems requires the careful consideration of redundancy for key components, rapid recovery in the event of partial system failures, and graceful degradation when problems occur. Performance: Website performance has become an important consideration for most sites. The speed of a website affects usage and user satisfaction, as well as search engine rankings, a factor that directly correlates to revenue and retention. As a result, creating a system that is optimized for fast responses and low latency is key. Reliability: A system needs to be reliable, such that a request for data will consistently return the same data. In the event the data changes or is updated, then that same request should return the new data. Users need to know that if something is written to the system, or stored, it will persist and can be relied on to be in place for future retrieval. Scalability: When it comes to any large distributed system, size is just one aspect of scale that needs to be considered. Just as important is the effort required to increase capacity to handle greater amounts of load, commonly referred to as the scalability of the system. Scalability can refer to many different parameters of the system: how much additional traffic can it handle, how easy is it to add more storage capacity, or even how many more transactions can be processed. Manageability: Designing a system that is easy to operate is another important consideration. The manageability of the system equates to the scalability of operations: maintenance and updates. Things to consider for manageability are the ease of diagnosing and understanding problems when they occur, ease of making updates or modifications, and how simple the system is to operate. (I.e., does it routinely operate without failure or exceptions?) Cost: Cost is an important factor. This obviously can include hardware and software costs, but it is also important to consider other facets needed to deploy and maintain the system. The amount of developer time the system takes to build, the amount of operational effort required to run the system, and even the amount of training required should all be considered. Cost is the total cost of ownership.
  • #5 Break down into front end and back end
  • #7 Javascript adoption with ES6, ‘don’t forget about babel’ Node.js: Swift 2: Apples vision for modern web programming Go: growing in popularity with startups TypeScript: Beauty of statically type Javascript (PS: Microsoft Technology)
  • #9 HTML: Creates the DOM CSS: Decorates the DOM JavaScript: Modifies the DOM Dynamically Back End Language: (PHP, Python, Ruby, F#): Generates the DOM on the fly
  • #10 MVC: separated (data model, logic, user interface) Push-based frameworks use actions that do the required processing, and then "push" the data to the view layer to render the results component-based: These frameworks start with the view layer, which can then "pull" results from multiple controllers as needed.
  • #11 HTML: Creates the DOM CSS: Decorates the DOM JavaScript: Modifies the DOM Dynamically Back End Language: (PHP, Python, Ruby, F#): Generates the DOM on the fly
  • #23 "…reusable building blocks for an application"