AngularJS - Meetup

AngularJS - Meetup

AngularJS Michael Kang August 20th 2015 Agenda Introduction AngularJS Features AngularJS Concept Map MVC Concepts Getting Started Data Binding Templating

Pluggable Architecture Dependency Injection Testability Conventions Examples Questions Introduction What is AngularJS

Why AngularJS? Improve Productivity Write Maintainable JavaScript Do More with Less Code One-Stop Framework Mobile Friendly Challenges JavaScript Framework for Building SPA applications Steep learning curve Objectives

Give you SPA powers! Teach Your Browser New Tricks! Have Fun! AngularJS Features Based on Model-View-Controller Pattern Modular Pluggable Architecture Well established pattern for building web applications Separates View concerns from Model concerns Striking similarities to ASP.NET MVC Powerful Data Binding Features

One-Way Data Binding Two-Way Data Binding Data Binding Expressions Flexible Templating Options Directive Templates Live Templates Transclusion Directives Filters Controllers

Services HTTP interceptors Form Validation Dependency Injection Services, Factories, Providers, Values, and Constants Testability Testing Services Testing Filters Interesting to Know Steep Learning Curve

Once you get it, you get! AngularJS is an unobtrusive, opinionated framework Use it well, or shoot yourself in the foot Potential for spaghetti code Plays very well with other frameworks Ask yourself, are you doing things the Angular Way? Paradigm shift. Thinking in Angular is different. Forget jQuery, and all the paradigms that come along with it Use jqLite, which is a light, subset of jQuery that is minimal and efficient

You can still use full jQuery, just include the library before AngularJS (not recommended) AngularJS Concept Map Term Concept Description One-Way Data Binding Pushing changes from the Model to the View Rendering a Model to HTML (i.e. Data Binding Expressions) Two-Way Data Binding Pushing changes from the Model to the View; Pushing changes from the View to the Model Rendering a Model to HTML; Collecting form data and saving it back to the Model (i.e. ngModel and HTML input fields) Model

A property of the View Model that the View can Data Bind to Models exist on Scope. Directives and Data Binding Expressions bind to Models on Scope. Directive Reusable View Plugin with accompanying behavior Directives can be an HTML element, attribute, CSS class or comment. They usually come with a template. Filter Pass object or collection through a filter and preserve original data format. AngularJS filters may be used for filtering, sorting, formatting, etc. i.e. currency, date, string formatting (uppercase, lowercase) Template The View concept from MVC. The View Engine processes the View Model and Renders the View. Directives with Templates are linked to Scope. The scope is the View Model. Directives are responsible for rendering Models on scope

inside of the template (i.e ngRepeat, ngIf, ngShow, etc) AngularJS Concept Map Term Concept Description Service The Model concept from the MVC pattern. Services are View-agnostic, and business-centric. AngularJS has services, factories, providers, values, and constants within the Model layer. All services (and their variants) are singletons. Dependency Injection Inject types into a constructor or function without worrying about how the type is created (or how its dependencies are managed) AngularJS uses Dependency Injection for all of its Services (and variants). Only certain functions are injectable: ngController, filters, directive definition objects, run blocks, etc. Child Scope

A shared View Model There is one Root Scope, and all child scopes inherit from each other and ultimately from Root Scope. Some directives will create child scopes, while others simply inherit scope. Scope properties are resolved through scope inheritance. Isolated Scope A private View Model This is the directives private sand-box. It does not participate in Scope inheritance. Bootstrap Initialization Process AngularJS is bootstrapped using the ngApp directive Controller The Controller concept from the MVC pattern. The Controller use the Model to retrieve the data, and then passed a View Model to the View. Repesented by ngControllers, and controller functions inside of a directive definition object. Transclusion

The process of injecting view sections into a Template. Taking the HTML contents of a directive, and plugging it into the views template. AngularJS Concept Map Term Concept Description Compilation Similar to recursive process of programming compilation. The process of traversing the DOM, searching for directives Linking Modules are linked together to form module dependencies. The process of linking Scope to the Directive, and adding dynamic behavior. MVC Concepts

Separation of View Concerns from Model Concerns View is responsible for sending requests to the controller and rendering the Views Model Controller is responsible for carrying out the Views requests by using the model services, and then formatting the Model data into a View Model for the View Model is responsible for exposing business services for the Controller Model View Controller - Example Model View Controller - Using Plugins Model View Controller - Conceptual Diagram Model View Controller - AngularJS

Getting Started Include AngularJS script (from www.angularjs.org) Add ngApp directive to bootstrap the application Typically on or tag One-Way Data Binding Changes to a Model property on Scope, will update the View Data Binding Expressions ( double curlies {{ }}) All View directives: ngIf, ngShow, ngRepeat Two-Way Data Binding ngModel on a select or input field will update the Model; and changes to the Model will update the View Data Binding Summary

Important Concept! Data Binding results in a Live View Changes to a Model is immediately reflected in the View (and vice versa) View and Model always in-sync All Models exist on Scope (properties of a View Model) Introduction to More Directives ngInit evaluate expressions on current Scope Tip: It is not good practice to use ngInit to initialize $scope (use ngController instead) In this example, ngInit is used just for demo purposes. In practice, ngInit is rarely used, except to alias

properties of ngRepeat Use ngRepeat to loop over an array, and apply a template with each iteration The syntax of the ngRepeat expression is [alias] in [array] Scope A View Model All child scopes inherit from $rootScope Directives may request and/or create child scope Inherits from parent scope (ngController, ngIf, ngRepeat, ngSwitch) The parent/child $scopes form a $scope hierarchy, ultimately inherits from $rootScope.

Models on a $scope are resolved through $scope inheritance Views data bind to Models which are properties of $scope $scope is created on an element, but requested by directives Two or more directives on the same element can all request a child scope, but share the same scope $scope is associated with the DOM element (at most 1) Controllers The C in MVC If ngApp has a value, then it refers to a named module

ngController refers to a named controller The named module must be defined The controller must be defined in the named module, or in any module listed as a dependancy The ngController function supports DI i.e The function is injectable ngControllers Initialize $scope for the View ngControllers always request a child $scope Controllers and Scope Directives that Create Child Scope It is useful to know which directives create child scopes

ngRepeat ngIf ngSwitch ngController Etc. Two or more directives can request a child scope on the same element. Both will share the same child scope. Tip!!! Visualize where your child $scopes are created, and on which $scope your Models are residing. This will help you when you design custom directives

Filters Use Filters for formatting, ordering, or filtering data Pipe character followed by filter name Filters can be chained Filters can be used inside Data Binding expressions You can create your own custom filters Filters do not change the original data source AngularJS built-in filters orderBy orders an array

uppercase formats text to Uppercase lowercase formats text to Lowercase json formats nicely to JSON limitTo limits the number of items date formats a date currency formats currency number formats numbers with decimal places Directives 4 kinds

Element Attribute CSS Class Comment A view plugin with dynamic behavior Anatomy of a Directive Restriction (element, attribute, CSS class, or comment) Transcluded Contents

Template (HTML View) Controller (ngController) View Model ($scope) Configured using a Directive Definition Object (DDO) Example Write a custom directive that makes any label editable: Clicking a label opens up a text box, where you can enter any text Two buttons appear: Ok and Cancel Clicking Ok changes the text; Clicking Cancel abandons the changes Templating

Directives may define a template The template is linked to a $scope Inherited Scope Child Scope Isolated Scope Template can optionally use Transclusion Element Transclusion (entire element is transcluded, template ignored) Content Transclusion (contents are transcluded) Directive Scopes

A directive can specify one of three kinds of scope: Inherited (default if none is specified) Child (requests a child scope) Isolated (private scope, does not inherit from any scope) $scope variables are passed from outer scope to isolated scope through elements attributes The scope definition object defines what the attributes represent: = Model @ String

& Method Directives - DDO Configuring a Directive with a Directive Definition Object (DDO): restrict property E (element directive) A (attribute directive) C (CSS class directive) M (comment directive) template/templateUrl property

scope property (defines the directives scope) {} (isolated scope) defines how attributes are imported into your directives scope true (child scope) requests child scope false (inherited scope) inherits from current scope transclude (access to the elements contents in your directives template) true (uses transclusion) false (does not use transclusion) compile Defines the HTML template

When angular traverses the DOM tree, matching directives, this is called compilation. When a directive is matched, it calls the directive compile function link When an element is linked to scope, the link function is called to add dynamic behavior Pluggable Architecture Easy to extend or write custom: Directives Controllers Filters Providers Factories

Services Values Constants Bundle into named modules More on this later Dependency Injection Services, Factories, Providers, Values, and Constants are injectable The following functions support injectables:

Factory Methods Factory Function Filter Function Directive Function Module Methods Run Block Config Block (only providers and constants) Controller Constructors ngController DDO Controller Service Constructors

Providers There are 5 flavors of Providers Service service function is an injectable constructor which is newed up and cached as an injectable dependency Factory return value of factory function is cached as an injectable dependency Value the object itself is cached as an injectable dependency. Value can be decorated, and injectable everywhere except configuration function. Constant the object itself is cached as an injectable dependency. Value cannot be decorated, but is injectable everywhere. Provider A configurable factory. The return value of the $get function is cached as an injectable dependency All providers are Singletons

One instance is created and cached The same instance is used wherever it is injected Providers are the primary means for controllers to get model data Modules A named module is defined by calling angular.module(name, dependencies) The first parameter is the name of the module, the second parameter is an array of module dependencies angular.module(app,[]) angular.module(app,[ngRoute,ngAnimate,ngMessages]) A module method returns an object, which you can use to bundle everything together:

var app = angular.module(app,[]); app.directive(); app.controller(); app.filter(); app.service(), app.factory(), app.value(); app.constant(); app.provider(); You can import the named module using the ngApp directive: Testability Testing Tools and Frameworks

Karma A command-line tool that spawns a browser to execute tests Jasmine Behavior driven development framework to support testing Angular-mocks Provides the ngMock module for mocking Angular services Supports Testing for Controllers Filters Directives Services Factories AngularJS Guide to Unite Testing

Conventions Directive Naming Conventions Directive names used inside of views are always snake case. i.e. ng-model Directives referred to inside of a DDO are always camel case. i.e. ngModel Module Naming Conventions Give your module a unique two-letter prefix. i.e. ng = angular i.e dm = demo For module filenames, use the fully expanded snake-case name

i.e. angular-route.js i.e. demo-tools.js For module definitions, use the abbreviated camel-case name i.e. ngRoute i.e. dmTools More Examples Write a custom filter that bolds and highlights the matched portion of the text yellow Should behave like a normal text filter i.e. include the record if any part of the text appears in the list, otherwise exclude it. Questions?

Recently Viewed Presentations

  • Basic Rifle Marksmanship

    Basic Rifle Marksmanship

    M4 RIFLE SYSTEM. Consists of a Rifle, a Magazine, and a Sling. It Is a Lightweight, Gas Operated, Air-Cooled, Magazine Fed Shoulder Fired Weapon That Can Be Fired Either in Semi-Automatic or Three Round Bursts.
  • 4.2 Congruence and Triangles - Council Rock School District

    4.2 Congruence and Triangles - Council Rock School District

    4.2 Congruence and Triangles Two geometric figures are congruent if they have exactly the same size and shape. When two figures are congruent corresponding angles are congruent and corresponding sides are congruent.
  • Parallelism, Multicore, and Synchronization

    Parallelism, Multicore, and Synchronization

    Unfortunately, we cannot not obtain unlimited scaling (speedup) by adding unlimited parallel resources, eventual performance is dominated by a component needing to be executed sequentially. Amdahl's Law is a caution about this diminishing return
  • The Design and Implementation of a Next Generation

    The Design and Implementation of a Next Generation

    The Design and Implementation of a Next Generation Name Service for the Internet
  • A New 2.0-6.0 GHz Chirped-Pulse Fourier Transform Microwave

    A New 2.0-6.0 GHz Chirped-Pulse Fourier Transform Microwave

    A New 2.0-6.0 GHz Chirped-Pulse Fourier Transform Microwave (CP-FTMW) Spectrometer: Instrumental Analysis & Initial Molecular Results. Nathan Seifert
  • Abt-sot - Gilar

    Abt-sot - Gilar

    Intensive diagnosis work-up if fever > 4d or recurrent fever 3 consecutive daily GM, chest CT, etc… AF if: proven-probable-possible IFI or persistent fever + « clinical deterioration »
  • Ch 33 Early 20th Century art - St. Johns County School District

    Ch 33 Early 20th Century art - St. Johns County School District

    CH 33 EARLY 20TH CENTURY ART The Development of Modernist Art Belgian painter Rene Magritte (1898-1967) -also expressed Surrealist images -dreamlike disassociation of image and meaning His works administer disruptive shocks because they subvert the viewer's expectations based on logic...
  • More on Telecommunications - Pearson Education

    More on Telecommunications - Pearson Education

    Chapter Topics The Transport Core Point-to-point TDM and SONET rings Increasingly, packet-switched ATM Signaling Supervisory communication, not voice transport Microwave and Satellite Transmission Building Telephone Wiring Versus Data Wiring The same for horizontal distribution on each floor (4 pair UTP)...