Presented by Venkatesh 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
• Google Chrome Development tools • Debugger to break into code in Chrome • AngularJS Batarang Debugging
• 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
• Advanced testing and debugging in AngularJS • Karma FAQ • Angular Style Guide • Why should you not use AngularJS? • Angular Fundamentals Sample Source References
• Send your feedback here Assessment and Evaluation

Angular js 1.0-fundamentals

  • 1.
    Presented by Venkatesh If youwish to have an in person training on AngularJS contact me at: @VenkiNarayanan AngularJS 1.0 – Fundamentals
  • 2.
    • Why AngularJS? • Controllers • Services • Directives • Dependency Injection • Routing • Getting data to and from your server • Testing your App • Digest Loop and $Apply Agenda
  • 3.
    • Javascript frameworkfor 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
  • 4.
    • Managing complexityof 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
  • 5.
    Angular – MV*framework Model View Controller / View Model
  • 6.
  • 7.
  • 8.
    • Hello World •Clock Sample 1
  • 9.
    • Module isentry 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
  • 10.
    • Scope referto 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
  • 11.
    • Controller isused 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
  • 12.
    • Expressions areused 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
  • 13.
    • Filters areused 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
  • 14.
    • Easy supportfor 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
  • 15.
    • Directives arecustom 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
  • 16.
    • Support formulti 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
  • 17.
    • Used toparse 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
  • 18.
    • Hashbang Mode– URL paths are prepended with # character • HTML 5 Mode – URLs looks like regular URLs Routing Modes
  • 19.
    • Why DependencyInjection ? ▫ 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
  • 20.
    • Responsible formanaging 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
  • 21.
    • Services enablesto 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
  • 22.
    • Use theservice 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
  • 23.
    • Provider isan 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
  • 24.
    • Standard decoratorpattern 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
  • 25.
    • Enables communicationwith 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
  • 26.
    • Enables interceptingall 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
  • 27.
    • $resource enablesto 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
  • 28.
    • Restangular isAngular 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
  • 29.
    • JSONP • CORS •Server Proxies Cross Origin / Same Origin Policy
  • 30.
    • Server siderendered 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
  • 31.
    • ExpressJs –NodeJs web application framework • Firebase • AngularFire Server Communication
  • 32.
    • 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
  • 33.
    • Digest Loop ▫$watch list ▫ $evalAsync list • $watch lists are resolved in the $digest loop – Dirty checking Digest Loop and $Apply
  • 34.
    • $watch objectis 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
  • 35.
    • When anychange 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
  • 36.
    • Used fordeferred 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
  • 37.
    • Used toexecute 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
  • 38.
    • Browser firesDOMContentLoaded 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
  • 39.
    Angular Architecture • DirectoryStructure – 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
  • 40.
    • Use $cacheFactoryservice for caching objects. • Support for default cache in $http service. • Support for custom cache to $http service. Caching
  • 41.
    • Google ChromeDevelopment tools • Debugger to break into code in Chrome • AngularJS Batarang Debugging
  • 42.
  • 43.
    • ngAnimate • UsesCSS3 for animation - Angular Animation
  • 44.
    • 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
  • 45.
    • 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
  • 46.
    • Expect –Expressionwe want to test • Matchers – Result of expectation, is validated by the matcher • Angular-ngMocks – Inject and mock services for unit test Unit testing - Jasmine
  • 47.
    • Ensure alldependencies 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
  • 48.
    • End toEnd 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
  • 49.
    • Mobile Apps ▫Apache Cordova (Phone Gap) • Chrome Apps Mobile / Chrome Apps with Angular JS
  • 50.
    • AngularJS powerfulclient 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
  • 51.
    • Advanced testingand debugging in AngularJS • Karma FAQ • Angular Style Guide • Why should you not use AngularJS? • Angular Fundamentals Sample Source References
  • 52.
    • Send yourfeedback here Assessment and Evaluation

Editor's Notes

  • #3 How presentation will benefit audience: Adult learners are more interested in a subject if they know how or why it is important to them. Presenter’s level of expertise in the subject: Briefly state your credentials in this area, or explain why participants should listen to you.
  • #5  Open source from Google Angular is MV* and opinionated Angular wants you to manipulate the DOM only from within the Directives. Within directives you can use jquery or plain javascript. Best software has vision. Best software takes sides. Supports unit tests and end to end tests Dirty Checking Dependency Injection
  • #6 There are other frameworks like: Knockout Backbone MV*, Open Source, Comprehensive, Testing Karma used for testing Extends HTML vocablary
  • #7 Need to have knowledge of DOM Angular JS gives MVC capability Expressive client side applications
  • #8 Everything starts with the controllers. Controllers contains the logic and the state Views / Directives communicate with the Controller using data binding. Services – Contains the real application state and the logic. Also it communicates with the server.
  • #9 Extend the sample demo with this input type example: <body ng-app="HelloWorldApp"> <input type="text" ng-model="name" placeholder="your name"> <h1 ng-controller="HelloWorldCtrl">Hello {{name}}</h1> </body> Briefly talk about the dirty checking. There is no change listeners attached. There are no events attached unlike in other frameworks.
  • #10 Do not pollute global namespace App can contain multiple modules and each module contains code specific functionality Provides isolation Need to define the name of the modules and the set of dependencies or the injectables.
  • #11 Methods in the controllers, properties in the views – Where the business functionality is defined Just before the App renders the view to the user, the view template links to the scope and the app sets up the DOM to notify angular for property changes. Provides ability to watch for model changes and propagate changes u sing the $apply mechanism When Angular starts to run and generate the view, it will create a binding from the root ng-app element to the $rootScope. This $rootScope is the eventual parent of all $scope objects. Look at $scope as view models
  • #12 The ng-click directive binds the mouseup browser click event to the method handler, which calls the method specified on the DOM element It is simply the glue between the view and the $scope model. One major distinction between AngularJS and other JavaScript frameworks is that the controller is not the appropriate place to do any DOM manipulation or formatting, data manipulation, or state maintenance beyond holding the model data. It is simply the glue between the view and the $scope model. Controllers can be nested and they inherit the scope object of the parent controllers.
  • #13 Has access to all the $scope variables. Angular expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{{ attrBinding }}">{{ textBinding }}</span>, but also used directly in directive attributes such as ng-click="functionExpression()".
  • #15 Ng-minlength, ng-maxlength for length validations
  • #16 Use ng-repeat to iterate over a collection and instantiate a new template for each item in the collection. Each item in the collection is given its own template and therefore its own scope. For instance, the ng-click directive gives an element the ability to listen for the click event and run an Angular expression when it receives the event. Directives are what makes the Angular framework so powerful, and, as we’ve seen, we can also create them.
  • #17 When there is a template associated with the current route: Create a new scope Remote the last view and that also cleans up the last scope Link the new scope to the new template Link the controller to the scope, if specified in the routes Emits the viewContentLoaded event Run the onload function if provided. Talk about controller, template vs templateUrl – Both would render the contents in the place of ng-view fafa
  • #18 Example redirection when the user signs up we need to redirect to the home page and we use the $location service .path .absUrl .hash .host .port .protocol
  • #19 Hashbang mode URL ex: http://yoursite.com/#!/inbox/all. You can configure it using $locationProvider.html5mode(false) and hasPrefix HTML5 URL looks like – http://yoursite.com/inbox/all Location service takes care of rewriting the URLs to hashbang if the HTML5 mode is not supported. Anything after #! Is for the client framework to interpret. When you switch from hashbang to html then your server should be able to server the Url.
  • #21 Annotation by Inference – Function parameter names are the names of the dependencies. Do toString, parse and extract the function arguments and use the $injector to inject these arguments into the instantiation of the object. Annotation by inference works only with non minified, non obfuscated code. Explicit Annotation – Explicit define the dependencies that a function needs upon invocation. Injection process uses the $inject property to annotate the function. $inject is an array of service names to inject as dependencies. Inline Annotation – Uses the $inject approach as in previous Explicit Annotation, but makes the arguments inline in the function definition. Allows us to pass an array of arguments instead of a function when defining an angular object Elements insider this array are the list of injectable dependencies as strings, the last argument being the function definition of the object. $inject API – Annotate – Returns the set of services that would injected into the function at time of invocation, get(name) – return an instance of the service, has(name) – whether a service instance exist or not,
  • #22 View is tied to the $scope and the controller manages the data using the $scope Controllers are created as needed and discarded when they are not. When we switch or reload a view the current controller gets cleaned up the Angular.
  • #23 Factory – Takes the name of the service and a function. Function is invoked once for the duration of the app lifecycle as its singleton. Factory can take an array for other injectable objects. Service – Instantiate a service using constructor function. Register a constructor function for service object. Provider – A separate $provider service can be used to create a new service. Factory is shorthand for creating service using provider service. Constant – Inject existing value as a service so that we can use it in other parts of the app. Value – Use value when the service would going to return a constant. Simplification of constant Difference between Constant and Value Constant can be used in the config section, whereus you cannot inject a value. Constants cannot be used for registering service objects or functions as the value Use value to register a service object or function, Use constant for configuration data.
  • #25 Use cases for decorating services include extending a service to cache external data requests to local storage or wrapping a service for debugging etc.
  • #26 Shortcut method for making get request using get call - $http.get() $http service invocation has to be passed with config object which provides details like the HttpMethod, Url, Params like headers $http uses the internal $cacheFactory for caching the data locally. $cacheFactory can be configured to use an lru cache. XHR = XML Http Request
  • #27 Enables global functionality on all requests – like authenticatin, error and logging etc. Handle Http 401 and redirecting the user to login page Request interceptor ex – Adding some specific headers Response interceptor – deserializing gzip compressed data When request interceptor throws error, it invokes the requestError
  • #28 Custom configuration objects are similar to $http configuration objects. $resource service can be the base for our custom services. Custom services gives better control in terms of abstract the responsibility of communicating to the remote services away from controllers and views Recommend to use the $resource inside a custom service object. Keeps the controllers clean.
  • #30 Same origin policy permits scripts to run on pages that originate from the same site Restrictions on accessing data from other / foreign domain. JSONP – Only for retrieval of data and predates CORS – Wrap the request with a callback function and response is wrapped in a callback. Where things get "magical" lies with the fact that a regular <script> tag does not have any limitations as to which domains it can pull down a script from. I could put a link to a JavaScript file on another domain in a <script> tag and it will download and immediately execute that script. JSONP is supported only for GET requests. CORS – Cross Origin Resource Sharing Enables XMLHttpRequest to make cross origin request. Built on top of CORS. (XMLHttpRequest2) Server side CORS requirements – Access Control Allow Origin – echo the origin header or * to allow all requests. CORS – Simple vs Non Simple Reqeusts – Simple request GET and POST. Non Simple – PUT and Delete Non Simple request – preflight and request. First the browser requests for permission using preflight and then the actual request. Acess-Control-Request-Method and then Access-Control-Allow-Origin Server side proxies – Instead of making cross origin request on the client, you make a call to the server and the server would fetch the required data. You need to setup the local server to fetch or handle our requests.
  • #31 In any web applications there are protected resources that is accessible only after authentication. We are not discussing the server side authentication here. For server side rendered views the auth is on the server. Token sent in every request from the client side to the server. All unauthenticated request the server should respond with HTTP 401. Unauthenticated user visits the site Access a protected resource. Redirect to the login page. User visit the page manually User enters his user id or login id and angular APP calls the server to get a token If the login is valid the server generates a token and sends it back. If the login does not match 401.
  • #32 Show the firebase example.
  • #34 Any time a field is bound from the $scope to the view, angular needs to track the change. It does by adding a watch function to the $watch list For all the UI elements that are bound to the $scope object, a watch function is added to the $watch list. Dirty Checking Walk down the list of watch function object. Compare its value to that of the value in the DOM. If the value has not changed, it moves to the next element. Rerun the watch list looping again to figure out whether any dependent value has changed. Rerun the watch list looping again
  • #36 1. ng-click binds the browser’s native click event to the DOM element. When that DOM element receives the click event, the ng-click directive calls $scope.$apply(), and we enter the $digest loop.
  • #37 If a directive calls $evalAsync() directly, it will run after Angular has manipulated the DOM, but before the browser renders. If a controller calls $evalAsync(), it will run before Angular has manipulated the DOM and before the browser renders (we’ll never really want to apply this order of events).
  • #38 The $apply() function executes an expression inside of the Angular context from outside of the Angular framework. Any time that we are handling an event manually, using a third-party framework (e.g., jQuery, the Facebook API), or calling setTimeout(), we want to use the $apply() function to tell Angular to rerun the $digest loop Do not use $apply in Controller since it makes it difficult to test. When integrating jQuery with Angular (an action generally considered dirty), we need to use $apply(), because Angular is not aware of events that execute outside of the Angular context. For instance, when using a jQuery plugin (e.g., the datepicker), we need to use $apply to transfer the value from jQuery into our Angular app.
  • #39 To manually bootstrap an AngularJS app, we can use the Angular method bootstrap(). It makes sense to manually bootstrap an application in some relatively rare cases. For instance, let’s say we want to run an AngularJS app after some other library code runs or we are dynamically creating an element on the fly. The Angular event loop is called the $digest loop. The $digest loop is composed of two small loops: the evalAsync loop and the $watch list.
  • #40 Modules The most obvious method for breaking up our app by modules is to divide the modules by type. Create a module for each Angular object type: Do not do DOM manipulation in controllers. Directives is the right place do that. Keep controllers thin Directives - The benefits of doing so are to have a single place where our DOM manipulation code is and also, to be able to unit test all these directives, since in many occasions lots of javascript code is not tested because is hard to test modules that involve the DOM. Share data using parent scope / root scope and have a proper hierarchy of controllers or services. Scope should be writeonly in the controllers, meaning the controller should use the service to fetch the data and populate the data in object scope. Do not create properties in the scope, but object. Scope is used bind model to the template.
  • #42 Google’s Chrome¹⁵⁸ has its own debugger tool to create a breakpoint in our code. The debugger statement will cause the browser to freeze during execution, allowing us to examine the running code from inside the actual application and at the point of execution inside the browser.
  • #44 Sample to show - http://codepen.io/EricSimons/pen/PwdKNE http://codepen.io/EricSimons/pen/KwxQpw http://codepen.io/EricSimons/pen/bNxrpK https://thinkster.io/angular-animations-tutorial
  • #45 Every piece of data that can change has a $watch on it. Each of these watches makes the digest loop to run longer. Minimize the number of watches can improve perf. For local changes invoke digest on the local scope. Instead of invoking digest on the root scope, invoke it on the local scope and only child scopes are impacted. Optimizing the page load – Minifcation, utilizing the template cache with pre-populated.
  • #46 Setting up of unit testing using – karma init test/karma.confg.js While building a unit test, it is important to include a testing framework like jasmine, custom test config., app specific code, test code, angular-mock.js E2E testing uses the ng-scenario framework and runs against the server . It loads all the test in the browser. Jasmine unit test framework – unit test based on behavior driven framework for Javascript Describe function describes a spec (logical grouping of tests)
  • #47 expect(true).toBe(true); expect(false).not.toBe(true); expect(1).toEqual(1); expect('foo').toEqual('foo'); expect('foo').not.toEqual('bar'); Mocha and Quint are other frameowrks in addition to Jasmine. Talk about Jasmine and how to use it for unit testing. Explain Sample: r Testing\SimpleCalculator Testing\AngularCalculator http://www.bradoncode.com/tutorials/angularjs-unit-testing/
  • #48 npm install karma --save-dev npm install -g karma-cli npm install karma-jasmine karma-chrome-launcher --save-dev karma init karma.conf.js Update package.json with the following: { "scripts": { "test": "karma start karma.conf.js" }, Start the test under npm test in CalculatorKarma folder.
  • #49 Install protractor - npm install -g protractor Use gulp to host the angulrjs app. Gulp is a java script runner. Install the selenium driver - webdriver-manager update, Start the selenium driver - webdriver-manager start protractor conf.js http://mherman.org/blog/2015/04/26/testing-angularjs-with-protractor-and-karma-part-2/#.VzSsrjahefA Sample: AngularFundamentals\Testing\ProtractorCalculator To show the demo do these: webdriver-manager start –standalone Gulp connect protractor conf.js
  • #50 1. ngTouch and Angular-touch
  • #51 Complexity of debugging