Angular js 1.0-fundamentals

52
Presented by Venkatesh If you wish to have an in person training on AngularJS contact me at: @VenkiNarayanan AngularJS 1.0 – Fundamentals

Transcript of Angular js 1.0-fundamentals

Page 1: Angular js 1.0-fundamentals

Presented byVenkatesh

If you wish to have an in person training on AngularJS contact me at: @VenkiNarayanan

AngularJS 1.0 – Fundamentals

Page 2: Angular js 1.0-fundamentals

•Why Angular JS?•Controllers•Services•Directives•Dependency Injection•Routing•Getting data to and from your server•Testing your App•Digest Loop and $Apply

Agenda

Page 3: Angular js 1.0-fundamentals

• Javascript framework for writing frontend web apps• Inspired by MVC pattern•Focus on supporting large and single page applications•Widely used▫Major rewrite in Version 2

What is AngularJS

Page 4: Angular js 1.0-fundamentals

•Managing complexity of JS on the client side•MVC paradigm •SRP – Separation of app. Logic, data model and views•Extend HTML Vocabulary•Two way data binding•Dependency Injection•Easily Testable

Why AngularJS

Page 5: Angular js 1.0-fundamentals

Angular – MV* framework

Model

View Controller / View Model

Page 6: Angular js 1.0-fundamentals

jQuery

Page 7: Angular js 1.0-fundamentals

Angular Components

Controllers Views / DirectivesServices

Page 8: Angular js 1.0-fundamentals

•Hello World•Clock

Sample 1

Page 9: Angular js 1.0-fundamentals

•Module is entry point for the AngularJs App•Keeping global namespace clean•Allow to load different parts of the app in any order•Example - angular.module('myApp', []);

Modules

Page 10: Angular js 1.0-fundamentals

•Scope refer to the application model• It is where we define the business logic of the application •Glue between the view and the controller. •Source of truth for the application state•$scope is the data model in Angular and are hierarchical

Scopes

Page 11: Angular js 1.0-fundamentals

•Controller is used to add custom behavior to the scope object•Controllers contain the logic of a single view. •Good practice to keep controllers slim. •Controller is not a place to do DOM manipulation or formatting of data•Custom functions on the scope object and bind to view actions•Controller Hierarchy

Controllers

Page 12: Angular js 1.0-fundamentals

•Expressions are used in the view.• {{ }} is an example of expression.•Expressions are executed in the context of local scope•Does not allow control flow statements•Accept filter or filter chains.

Expressions

Page 13: Angular js 1.0-fundamentals

•Filters are used to format the data displayed to the user.•Several built in filters and also ability to create your own filter.•Multiple filters can be combined using the pipes operator (|)•Standard Filters: currency, date, string filtering, json, orderby•Custom filters – Example

Filters

Page 14: Angular js 1.0-fundamentals

•Easy support for client side validations•Support for HTML5 form validation inputs and Angular specific

validation directives•Access to control variables in forms –

formName.inputFieldName.propery

Form Validations

Page 15: Angular js 1.0-fundamentals

•Directives are custom HTML elements and attributes•Directives are functions that we run on a particular DOM element.•Directives creates an isolated scope•Built in directives (ng-href, ng-src etc)•Directives with child scope▫Ng-app▫Ng-controller▫Ng-repeat

Directives

Page 16: Angular js 1.0-fundamentals

•Support for multi page Apps. •Break the view into layout and template views•Show only the view we want to show based on URL•Angular enables this using $routeProvider service.•Ng-view – Special directive for activing as placeholder for view content.

Multiple Views and Routing

Page 17: Angular js 1.0-fundamentals

•Used to parse the URL and provides access to the route of current path•Provides ability to change paths and deal with navigation•Use $location service whenever you need to redirect internally to the

app.

$location Service

Page 18: Angular js 1.0-fundamentals

•Hashbang Mode – URL paths are prepended with # character•HTML 5 Mode – URLs looks like regular URLs

Routing Modes

Page 19: Angular js 1.0-fundamentals

•Why Dependency Injection ?▫Create internally to a dependent.▫Look up or refer global variable▫Pass it on where its needed.

•Removes hard-coded dependencies•Remove or change it at run-time•Enables testing – real vs mocked objects

Dependency Injection

Page 20: Angular js 1.0-fundamentals

•Responsible for managing lookups and instantiation of dependencies•All angular components (app modules, controllers, directives)• Injector responsible for creating instance of the object and passing in.•Annotation types:▫Annotation by Inference▫Explicit Annotation▫Inline Annotation

Angular $Injector

Page 21: Angular js 1.0-fundamentals

•Services enables to keep the data around for lifetime of the App•Enables to communicate across controllers in uniform way•Services are singleton objects that are lazy loaded.•Factory interface is used to register a service. •Service factory function is used for generating a function or object that

becomes service.

Services

Page 22: Angular js 1.0-fundamentals

•Use the service as a dependency on controller, directive or another service.

•Pass the name as argument to the controller function. •Options for creating services:▫Factory()▫Service()▫Provider()▫Constant()▫Value()

Using Services

Page 23: Angular js 1.0-fundamentals

•Provider is an object with a $get method•$injector calls the $get method to create a new instance of service.•Root method – provider() – Responsible for registering with provider

cache•Factory is shorthand for creating service using the provider() method.•Provider is mainly used for configuring a service using the

angular .config() function.

$provider service

Page 24: Angular js 1.0-fundamentals

•Standard decorator pattern implementation•Used to intercept service instance creation.•Can be used to extend or replace the functionality entirely.•Can be used to intercept, interrupt and replace functionality in core

angular services.•Many of angular testing is enabled using $provider.decorator()

$decorator service

Page 25: Angular js 1.0-fundamentals

•Enables communication with the backend server for fetching data.•$http service is wrapper for XMLHttpRequest•$http requests supports caching of request in local cache.

XHR and Server side communication

Page 26: Angular js 1.0-fundamentals

•Enables intercepting all requests to the server and back from the server.•Middleware for $http service •Allows to inject logic into existing flow of the App.•4 types of interceptors▫Request▫Response▫Request Error▫Response Error

•Use factory() to create an interceptor

Interceptors

Page 27: Angular js 1.0-fundamentals

•$resource enables to create a resource object for RESTful server-side data sources

•Abstracts interacting with RESTful data model.•$resource is an abstraction above $http.•Requires ngResource module (angular-resource).•Provides helper methods – get, query, save, delete (remove)•Resource instances provides save, delete / remove•Support for custom $resource methods and custom configuration

objects

$resource service

Page 28: Angular js 1.0-fundamentals

•Restangular is Angular service to fetch data from RESTful services•Uses Promises•Supports all HTTP methods•Support for E-Tags out of the box•Unlike $resource, there is no need to remember the Url.•Enables to create your own methods

Restangular

Page 29: Angular js 1.0-fundamentals

• JSONP•CORS•Server Proxies

Cross Origin / Same Origin Policy

Page 30: Angular js 1.0-fundamentals

•Server side rendered views•Client side authentication▫Tracking whether the user is authenticated or not▫Handling public vs non-public / protected resource▫Use route events to handle protected resources.

Authentication in AngularJS

Page 31: Angular js 1.0-fundamentals

•ExpressJs – NodeJs web application framework •Firebase•AngularFire

Server Communication

Page 32: Angular js 1.0-fundamentals

•Compile Phase ▫Processing of the directives▫Deals with transforming the template DOM

• Link Phase▫Deals with linking scope to the DOM

Angular JS Life Cycle

Page 33: Angular js 1.0-fundamentals

•Digest Loop▫$watch list▫$evalAsync list

•$watch lists are resolved in the $digest loop – Dirty checking

Digest Loop and $Apply

Page 34: Angular js 1.0-fundamentals

•$watch object is to setup to check for dirty state•$watch takes two arguments:▫Watch Expresssion – Property of scope object or function▫Listener/callback – Invoked when the current value and previous value of

watch expression are different.•$watch returns a deregistration function to cancel the watch.

$watch

Page 35: Angular js 1.0-fundamentals

•When any change is detected, the digest loop is started•Starts iterating through the $watchers and marking dirty•Re-run of the digest loop to check for any dependent change•At the end of digest loop, browser repaints the DOM and refresh the

view.• In case of native event to the DOM element, ng-click directive calls

$scope.apply and that triggers the digest loop again.

$digest Loop

Page 36: Angular js 1.0-fundamentals

•Used for deferred executions of an expression.•$evalAsync makes the following guarantees:▫It will be executed after the function that scheduled the evaluation▫At least one $digest cycle will be performed after expression execution.

•dfa

$evalAsync list

Page 37: Angular js 1.0-fundamentals

•Used to execute an expression in angular context•$apply directly calls the digest loop•Provides a way to gain access to angular context from outside.•Example usage of $apply:▫$http service calls $apply after XHR is completed▫Anytime we are handling event manually, we instruct angular to run

$digest loop.▫Integrating with jQuery where we want to transfer value from datepicker to

angular app.

$apply

Page 38: Angular js 1.0-fundamentals

•Browser fires DOMContentLoaded and then Angular starts.• Looks for ng-app directive to boostrap and load the specific module•Uses the ng-app directive to configure the $injector service•$injector service creates the $compile service and the $rootscope• Links the $rootscope with the DOM and starts compiling the DOM from

where ng-app is set.•$compile phase traverse DOM to figure out all the directives. Linking

phase it links the template to the rootscope.• Linking phase sets up the watches on the directives

Angular Bootstrapping

Page 39: Angular js 1.0-fundamentals

Angular Architecture•Directory Structure – Consider Angular Seed / Yeoman•Modules ▫Modularize on functionality ▫Modularize on routes

•Controllers•No properties in Scope but objects•Extension of the HTML - Directives•Think Dependency Injection – Testing

Page 40: Angular js 1.0-fundamentals

•Use $cacheFactory service for caching objects.•Support for default cache in $http service. •Support for custom cache to $http service.

Caching

Page 42: Angular js 1.0-fundamentals

•Angular-Translate•TBD

Localization

Page 43: Angular js 1.0-fundamentals

•ngAnimate •Uses CSS3 for animation -

Angular Animation

Page 44: Angular js 1.0-fundamentals

•Optimizing the $digest loop• Limit the number of data bindings (max 2000)•Optimizing on ng-repeat - one data binding per entry in the list.•Optimizing the $digest call•Optimizing the $watch functions•Avoid unnecessary filters.

Optimizing Angular Apps

Page 45: Angular js 1.0-fundamentals

•Karma – Test framework for JS•Enables running tests in different browser instances and environments•Types of Angular Tests▫Unit Testing

Karma & Jasmine – BDD for JS▫E2E Testing

Protractor -

Testing

Page 46: Angular js 1.0-fundamentals

•Expect –Expression we want to test•Matchers – Result of expectation, is validated by the matcher

•Angular-ngMocks – Inject and mock services for unit test

Unit testing - Jasmine

Page 47: Angular js 1.0-fundamentals

•Ensure all dependencies installed – karma, karma-jasmine, karma-firefox-launcher

•Verify package.json has the required packages• Initialize the karma.conf.js using the karma init command.•Define the test.js file and include it in the karma.conf.js•Add the karma start karma.conf.js•Good reference on Unit testing with Karma is here

Karma for Angular Unit testing

Page 48: Angular js 1.0-fundamentals

•End to End test framework for AngularJs in NodeJs.•Supports Jasmine and Mocha test framework•Running Protractor sample:▫Install Protractor▫Use Gulp to host the angular App.▫Install the selenium driver▫Define the config file with the test spec.js▫Run the tests

•Reference - http://www.protractortest.org/#/

Protractor for E2E testing

Page 49: Angular js 1.0-fundamentals

•Mobile Apps▫Apache Cordova (Phone Gap)

•Chrome Apps

Mobile / Chrome Apps with Angular JS

Page 50: Angular js 1.0-fundamentals

•AngularJS powerful client side web framework.•Angular 2.0 changes most of the concepts. ▫Most of what you learnt here won’t be applicable in 2.0.

•Understand the performance implications for complex data intensive web apps

•Backward compatibility between V1 and V2 is not there.

Summary