Angular js 1.0-fundamentals

Post on 09-Apr-2017

240 views 0 download

Transcript of 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

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

Agenda

• 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

•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

Angular – MV* framework

Model

View Controller / View Model

jQuery

Angular Components

Controllers Views / DirectivesServices

•Hello World•Clock

Sample 1

•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

•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

•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

•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

•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

•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

•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

•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

•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

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

Routing Modes

•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

•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

•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

•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

•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

•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

•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

•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

•$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

•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

• JSONP•CORS•Server Proxies

Cross Origin / Same Origin Policy

•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

•ExpressJs – NodeJs web application framework •Firebase•AngularFire

Server Communication

•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

•Digest Loop▫$watch list▫$evalAsync list

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

Digest Loop and $Apply

•$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

•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

•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

•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

•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

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

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

Caching

•Angular-Translate•TBD

Localization

•ngAnimate •Uses CSS3 for animation -

Angular Animation

•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

•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

•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

•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

•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

•Mobile Apps▫Apache Cordova (Phone Gap)

•Chrome Apps

Mobile / Chrome Apps with Angular JS

•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