AngularJS. Beginner's guide - part 2

Similar documents
AngularJS AN INTRODUCTION. Introduction to the AngularJS framework

AngularJS. Beginner's guide - part 1

AngularJS Introduction

3 Days Training Program

Single Page Applications

Prototyping a Social Network. AngularJS: Firebase integration with AngularFire

Tim Roes. Android- & inovex in Karlsruhe. GDG Karlsruhe Co-Organizer.

What is AngularJS. à Javascript Framework à MVC à for Rich Web Application Development à by Google

Frontend Frameworks. SWE 432, Fall 2016 Design and Implementation of Software for the Web

Nagaraju Bende

Getting Started with

Lazy Loading Techniques

AngularJS Fundamentals

Web Architecture AN OVERVIEW

Python INTERMEDIATE. Rapid prototyping using Python libraries and integration with local and remote services

Introduction to AngularJS

Introduction and first application. Luigi De Russis. Rails 101

Design and Implementation of Single Page Application Based on AngularJS

Financial. AngularJS. AngularJS. Download Full Version :

Comprehensive AngularJS Programming (5 Days)

ANGULARJS - MOCK TEST ANGULARJS MOCK TEST II

ANGULARJS INTERVIEW QUESTIONS

Financial. AngularJS. AngularJS.

User Interaction: jquery

AJAX ASYNCHRONOUS JAVASCRIPT AND XML. Laura Farinetti - DAUIN

AngularJS. CRUD Application example with AngularJS and Rails 4. Slides By: Jonathan McCarthy

AngularJS. CRUD Application example with AngularJS and Rails 4. Slides By: Jonathan McCarthy

JavaScript Framework: AngularJS

Understanding Angular Directives By Jeffry Houser

HTML DOM IN ANGULARJS

Git AN INTRODUCTION. Introduction to Git as a version control system: concepts, main features and practical aspects.

THE HITCHHIKERS GUIDE TO. Harper Maddox CTO, EdgeTheory 30 September 2014

ngphotos (Grails + AngularJS)

Ruby AN OVERVIEW. Luigi De Russis Dipartimento di Automatica e Informatica Politecnico di Torino

Lab 1 - Introduction to Angular

Templates and Databinding. SWE 432, Fall 2017 Design and Implementation of Software for the Web

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

Web Application Development

Building Web Applications

AngularJS Intro Homework

Input and Validation. Mendel Rosenblum. CS142 Lecture Notes - Input

Ajax- XMLHttpResponse. Returns a value such as ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, based on the value of

Questions and Answers from Lukas Ruebbelke s AngularJS In-Depth Course

Single Page Applications using AngularJS

Angular 2 Programming

Sample Copy. Not For Distribution.

Anatomy of an HTML document

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains an Individual and Group component

Motivations. Luigi De Russis. Why Ruby (on Rails)?

Connecting Angular and CFML

JSON POST WITH PHP IN ANGULARJS

Full Stack Web Developer

Introduction to TypeScript

Modern and Responsive Mobile-enabled Web Applications

Data-Centric Single Page Apps with Angular, Web API, and Breeze

MEAN Stack. 1. Introduction. 2. Foundation a. The Node.js framework b. Installing Node.js c. Using Node.js to execute scripts

Comprehensive Angular 2 Review of Day 3

Full Stack boot camp

Quick Desktop Application Development Using Electron

Creating Effective Websites using AngularJS

Angular 4 Syllabus. Module 1: Introduction. Module 2: AngularJS to Angular 4. Module 3: Introduction to Typescript

PHP / MYSQL DURATION: 2 MONTHS

Sample CS 142 Midterm Examination

Controller/server communication

CodeValue. C ollege. Prerequisites: Basic knowledge of web development and especially JavaScript.

Simple AngularJS thanks to Best Practices

Controller/server communication

A Model-Driven Development of Web Applications Using AngularJS Framework

a Very Short Introduction to AngularJS

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains 2 components

HTML5 Drag &Drop API. For better interfaces. Laura Farinetti - DAUIN

Angular 4 Training Course Content

Dynamic Web Development

The course also includes an overview of some of the most popular frameworks that you will most likely encounter in your real work environments.

UNIVERSITY OF TORONTO Faculty of Arts and Science DECEMBER 2015 EXAMINATIONS. CSC309H1 F Programming on the Web Instructor: Ahmed Shah Mashiyat

BOOSTING THE SECURITY OF YOUR ANGULAR 2 APPLICATION

DECOUPLING PATTERNS, SERVICES AND CREATING AN ENTERPRISE LEVEL EDITORIAL EXPERIENCE

Course Details. Skills Gained. Who Can Benefit. Prerequisites. View Online URL:

Manual Html A Href Onclick Submit Form

About Me. Name: Jonathan Brown. Job: Full Stack Web Developer. Experience: Almost 3 years of experience in WordPress development

Lesson 12: JavaScript and AJAX

תוכנית יומית לכנס התכנסות וארוחת בוקר

! The final is at 10:30 am, Sat 6/4, in this room. ! Open book, open notes. ! No electronic devices. ! No food. ! Assignment 7 due 10pm tomorrow

CS142 Winter 2017 Midterm Grading Solutions and Rubric

HTML5 INTRODUCTION & SEMANTICS

Full Stack Web Developer

AJAX: The Basics CISC 282 November 22, 2017

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

IN ACTION. Lukas Ruebbelke. FOREWORD BY Martin Gontovnikas MANNING SAMPLE CHAPTER

HTML5 INTRODUCTION & SEMANTICS

EXPRESSIONS IN ANGULARJS

Databases in Python. MySQL, SQLite. Accessing persistent storage (Relational databases) from Python code

KonaKart Shopping Widgets. 3rd January DS Data Systems (UK) Ltd., 9 Little Meadow Loughton, Milton Keynes Bucks MK5 8EH UK

Ten interesting features of Google s Angular Project

AJAX: The Basics CISC 282 March 25, 2014

HTML5 INTRODUCTION & SEMANTICS

Web Architecture and Technologies

JavaScript Patterns O'REILLY* S toy an Stefanov. Sebastopol. Cambridge. Tokyo. Beijing. Farnham K8ln

PRAjax PHP Reflected Ajax Developer Manual

ANGULAR2 OVERVIEW. The Big Picture. Getting Started. Modules and Components. Declarative Template Syntax. Forms

Transcription:

AngularJS Beginner's guide - part 2

Summary of the previous lesson 1. To add AngularJS to an empty page: a) Download the script angular.js from https://angularjs.org/ b) Link it in the header <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul ar.min.js" ></script> c) Add the ng-app directive to the portion of the page that AngularJS should process <html lang="en" ng-app>... 2

Summary of the previous lesson 2. To create a controller that implements the logic of your app: a) Declare the module in your HTML page <html lang="en" ng-app="sonetexample" > b) Create a JavaScript file (example.js) containing the module and the controller declaration angular.module("sonetexample", []) }).controller('myctrl', function ($scope) { //do something 3

Summary of the previous lesson c) Link it in the HTML header d) Use the ng-controller directive to say to AngularJS in which part of the page it should be used e) Modify the script (example.js) to actually implement the controller actions angular.module("sonetexample", [] ).controller('myctrl', function ($scope) { }) <script src= "./example.js" ></script> <body ng-controller="myctrl"> $scope.name = "Teo"; 4

Summary of the previous lesson 3. To share data between the controller and the view: Use the $scope angular.module("sonetexample", []).controller('myctrl', function ($scope) {... }) Example 5 and 6 5

Routing Single page applications need routing to mimic static addresses (http://mysite.com/...) to manage browser history Goal: load different views into the single page app 6

Routing in AngularJS Goal: load different views into a portion of the single page app TitleBar Menu ng-view 7

How: ngroute Angular API for routing Provides a directive to indicate where view component should be inserted in the template (ngview) a service that watches window.location for changes and updates the displayed view ($route) a configuration that allows the user to specify the URL to be used for a specific view ($routeprovider) It is located in a dedicated js file angular-route.min.js 8

How to use ngroute In a template <div ng-view></div> In your Angular module, add ngroute as a dependency angular.module('sonetexample', [ngroute]) Now our application has access to the route module, which provides the $routeprovider Configure the routing table in a config block.config(['$routeprovider', function($routeprovider) { }]) Example 7 9

How to use ngroute In a template <div ng-view></div> In your Angular module, add ngroute as a dependency angular.module('sonetexample', [ngroute]) Now our application has access to the route module, which provides the $routeprovider Configure the routing table in a config block.config(['$routeprovider', function($routeprovider) { }]) Every time we use an external module we have to specify it in the module dependencies Example 7 10

How to use ngroute In a template <div ng-view></div> In your Angular module, add ngroute as a components, too! In dependency this case we have to use methods angular.module('sonetexample', provided by the routeprovider, [ngroute]) so Now our application we declare has its access dependency to the route module, which provides the $routeprovider Configure the routing table in a config block.config(['$routeprovider', function($routeprovider) { }]) Dependencies are important for other Example 7 11

How to use ngroute: Example7 example7.html: <!DOCTYPE html> <html lang="en" ng-app="sonetexample7"> <head> <meta charset="utf-8"> <title>routing and Views</title> <script src="./angular.min.js"></script> <script src="./angular-route.min.js"></script> <script src="./example7.js"></script> </head> <body> <div ng-view></div> </body> </html> 12

How to use ngroute: Example7 enter-name.html: <div> <label>name</label> <input type="text" ng-model="name" placeholder="enter your name"> </div> <h1>{{ greeting }} {{name}}!</h1> 13

How to use ngroute: Example7 example7.js: angular.module("sonetexample7", ['ngroute']).config(['$routeprovider', function ($routeprovider) { $routeprovider.when('/name', { templateurl: 'enter-name.html', controller: 'MyCtrl' }).otherwise({redirectto: '/name'}); }]).controller('myctrl', function ($scope) { $scope.name = ""; $scope.greeting = "Ciao"; }); 14

How to use ngroute: Example7 example7.js: angular.module("sonetexample7", ['ngroute']).config(['$routeprovider', function ($routeprovider) { $routeprovider.when('/name', { templateurl: 'enter-name.html', controller: 'MyCtrl' }).otherwise({redirectto: '/name'}); }]).controller('myctrl', function ($scope) { $scope.name = ""; $scope.greeting = "Ciao"; }); Here the controller is specified in an internal method 15

Passing parameters in URLs URLs: #/pizzas/my-pizza #/pizzas/another-pizza Routing table configuration:.config(['$routeprovider', function ($routeprovider){ $routeprovider.when('/pizzas/:pizzaid', { templateurl: 'single-pizza.html', controller: 'PizzaCtrl', }) [...] }]) JS 16

Passing parameters in URLs Controller:.controller('PizzaCtrl', ['$routeparams', function ($routeparams) { $routeparams.pizzaid // will be my-pizza or another-pizza }) JS 17

Services Responsible to hold the model and communicate with a server Singleton objects that are instantiated only once per app and lazy loaded controllers are instantiated only when they are needed and discarded otherwise 18

Built-in Services Server communication $http, $resource, Wrapping DOM access $location, $window, $document, JavaScript functionality $animate, $log, 19

The $http Service Uses the XMLHttpRequest object (or JSONP) to communicate with a server How it works takes a single argument: a configuration object returns a promise with two methods: success() and error() It can use the.then() method, too it registers a dedicated callback for the success and error method 20

The $http Service $http({ }) method: 'GET', promise url: '/someurl'}).success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available }).error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. }); JS callbacks 21

The $http Service Shortcut methods var sonet = angular.module('sonetexample', []); JS sonet.controller('myctrl', ['$scope', '$http', function ($scope, $http) { var promise = $http.get('/pizzas.json'); promise.success(function(data) { $scope.pizzas = data; }); } ]); Shortcut methods:.get(),.post(),.put(),.delete(), etc. 22

$http in a Custom Service // custom service sonet.factory('pizza', function($http) { var pizzaservice = { getdata: function () { return $http.get('/pizzas.json').then(function (response) { return response.data; }); } }; return pizzaservice; }) // controller sonet.controller('pizzactrl', ['$scope', 'Pizza', function ($scope, Pizza) { Pizza.getData().then(function(pizzaList) { $scope.pizzas = pizzalist; }); } ]); JS Example 8 23

The $resource Service Replace the "low level" $http service it has methods with high-level behaviors but the server URLs must be RESTful REST: REpresentational State Transfer works on the concept of resource CRUD: Create, Read, Update and Delete read a collection of resources: read a single resource: add a new resource: update an existing resource: delete an existing resource: GET /pizzas GET /pizzas/:id POST /pizzas PUT /pizzas/:id DELETE /pizzas/:id 24

The $resource Service Requires the ngresource module to be installed No callbacks needed! e.g., $scope.pizzas = pizzaservice.query(); Available methods get(), method: GET, single resource query(), method: GET, is array (collection) save(), method: POST remove(), method: DELETE, delete(), method: DELETE 25

Other best practices in AngularJS BEST PRACTICES 20/04/2017 26

A dot in the model "There should always be a dot in your model" Parent scope: $scope.name = "Anon" Child scope: <input type="text" ng-model="name"> The application will display "Anon" initially, but once the user changes the value a name will be created on the child scope and the binding will read and write that value. The parent's name will remain "Anon". This can cause problems in large applications. To avoid them: <input type="text" ng-model="person.name"> 27

camelcase vs dash-case You can use variable named like my-variable myvariable The latter can cause problems in HTML it is case-insensitive Angular solution: use either, it will map them to the same thing Use dash-case in HTML and camelcase in JavaScript 28

ADDITIONAL INFORMATION 20/04/2017 29

Custom Directives Application specific replace HTML tags with functional tags you define e.g., DatePicker, Accordion,... Naming Camel case naming (ngrepeat) automatically mapped to ng-repeat, data-ngrepeat in the templates e.g., <div ng-repeat></div> 30

Custom Directives A directive returns an object (directive definition) with several properties details: https://docs.angularjs.org/api/ng/service/$compile var sonet = angular.module('sonetexample', []); JS sonet.directive('helloheader', function() { return { restrict: 'E', template: '<h2>hello World!</h2>' }; }); 31

Custom Directives var sonet = angular.module('sonetexample', []); JS sonet.directive('helloheader', function() { return { restrict: 'E', template: '<h2>hello World!</h2>' }; }); Restricts the directive to a specific HTML "item". If omitted, the defaults (Elements and Attributes) are used. 32

Custom Directives var sonet = angular.module('sonetexample', []); JS sonet.directive('helloheader', function() { return { restrict: 'E', template: '<h2>hello World!</h2>' }; }); replace or wrap the contents of an element with this template 33

Compile and Link Named after the two phases Angular uses to create the live view for your application Compile looks for all the directives and transforms the DOM accordingly, then calls the compile function (if it exists) Link makes the view dynamic via directive link functions the link functions typically create listeners on the DOM or the model; these listeners keep the view and the model in sync at all times scopes are attached to the compiled link functions, and the directive becomes live through data binding 34

Link Function: Example var sonet = angular.module('sonetexample', []); sonet.directive('backbutton', ['$window', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { elem.bind('click', function () { $window.history.back(); }); } }; }]) JS 35

References AngularJS official guide https://docs.angularjs.org/guide AngularJS API documentation https://docs.angularjs.org/api AngularJS in 60 minutes [video] https://www.youtube.com/watch?v=i9mhiguzkem Learn Angular in your browser http://angular.codeschool.com/ 36

01QYAPD SOCIAL NETWORKING: TECHNOLOGIES AND APPLICATIONS My contact information: Teodoro Montanaro (teodoro.montanaro@polito.it) Thanks to Luigi De Russis (luigi.derussis@polito.it), the creator the slides I used as basis!

License This work is licensed under the Creative Commons Attribution- NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0) License. You are free: to Share - to copy, distribute and transmit the work to Remix - to adapt the work Under the following conditions: Attribution - You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Noncommercial - You may not use this work for commercial purposes. Share Alike - If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. To view a copy of this license, visit http://creativecommons.org/license/by-nc-sa/3.0/ 38