Download presentation
Presentation is loading. Please wait.
1
AngularJS Michael Kang August 20th 2015
2
Agenda Introduction AngularJS Features AngularJS Concept Map
MVC Concepts Getting Started Data Binding Templating Pluggable Architecture Dependency Injection Testability Conventions Examples Questions
3
Introduction What is AngularJS Why AngularJS? Challenges Objectives
JavaScript Framework for Building SPA applications Why AngularJS? Improve Productivity Write Maintainable JavaScript Do More with Less Code One-Stop Framework Mobile Friendly Challenges Steep learning curve Objectives Give you SPA powers! Teach Your Browser New Tricks! Have Fun!
4
AngularJS Features Based on Model-View-Controller Pattern
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 Modular Pluggable Architecture Directives Filters Controllers Services HTTP interceptors Form Validation Dependency Injection Services, Factories, Providers, Values, and Constants Testability Testing Services Testing Filters
5
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)
6
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)
7
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 directive’s 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.
8
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.
9
MVC Concepts Separation of View Concerns from Model Concerns
View is responsible for sending requests to the controller and rendering the View’s Model Controller is responsible for carrying out the View’s 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
10
Model View Controller - Example
11
Model View Controller - Using Plugins
12
Model View Controller - Conceptual Diagram
13
Model View Controller - AngularJS
14
Getting Started Include AngularJS script (from www.angularjs.org)
Add ngApp directive to bootstrap the application Typically on <html> or <body> tag
15
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
16
Two-Way Data Binding ngModel on a select or input field will update the Model; and changes to the Model will update the View
17
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)
18
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]”
19
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)
20
Controllers The “C” in MVC
If ngApp has a value, then it refers to a named module The named module must be defined ngController refers to a named controller 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
21
Controllers and Scope
22
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
23
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
24
Directives 4 kinds A view plugin with dynamic behavior
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)
25
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
26
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)
27
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 element’s attributes The scope definition object defines what the attributes represent: = Model @ String & Method
28
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 Defines the HTML template scope property (defines the directive’s scope) {} (isolated scope) defines how attributes are imported into your directive’s scope true (child scope) requests child scope false (inherited scope) inherits from current scope transclude (access to the element’s contents in your directive’s template) true (uses transclusion) false (does not use transclusion) compile 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
29
Pluggable Architecture
Easy to extend or write custom: Directives Controllers Filters Providers Factories Services Values Constants Bundle into named modules More on this later…
30
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
31
Providers There are 5 flavors of Providers
Service – service function is an injectable constructor which is new’ed 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
32
Modules A named module is defined by calling angular.module(name, dependencies) angular.module(‘app’,[]) The first parameter is the name of the module, the second parameter is an array of module dependencies 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: <html ng-app=“app”>
33
Testability Testing Tools and Frameworks Supports Testing for
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
34
Conventions Directive Naming Conventions Module 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
35
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.
36
Questions?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.