• No results found

angularjs notes.docx

N/A
N/A
Protected

Academic year: 2021

Share "angularjs notes.docx"

Copied!
11
0
0

Loading.... (view fulltext now)

Full text

(1)

Problem: HTML is good for static content. For dynamic content, a DOM manipulation library is Problem: HTML is good for static content. For dynamic content, a DOM manipulation library is required.

required.

olution: !ngular" e#tends HTML and ma$e it dynamic using declarati%e synta#. olution: !ngular" e#tends HTML and ma$e it dynamic using declarati%e synta#. &reat for ingle Page !pplications 'P!( and )*+D applications.

&reat for ingle Page !pplications 'P!( and )*+D applications. +ses

+ses M- 'Modelie/-0ate%er(M- 'Modelie/-0ate%er( frame/or$ on t0e +1. frame/or$ on t0e +1. eparates HTML DOM references from t0e "a%acript eparates HTML DOM references from t0e "a%acript Pro%ides tools for +1 testing.

Pro%ides tools for +1 testing. )rossbro/ser compatible. )rossbro/ser compatible. &reat t0ird party modules li$e

&reat t0ird party modules li$e !ngular+1!ngular+1..

M)

M): or MM or /0ate%er 'M-(.: or MM or /0ate%er 'M-(. Model

Model:: The Model is simply the The Model is simply the data in the application and is just plain old data in the application and is just plain old JavaScript objects.JavaScript objects.ModalModal represents business data. The view is a projection of the model at any given time.

represents business data. The view is a projection of the model at any given time.

ie/:

ie/: The View is the HTML that exists after Angular! has parsed and compiled theThe View is the HTML that exists after Angular! has parsed and compiled the HTML to in

HTML to include rendered clude rendered mar"up#directimar"up#directives$ and ves$ and bindings.bindings. %ou can thin" of the view as%ou can thin" of the view as simply an instant projection of your model.

simply an instant projection of your model.

1t s0ould update itself /0ene%er t0e underlying data model c0anges. 1n !ngular" t0e %ie/ reads 1t s0ould update itself /0ene%er t0e underlying data model c0anges. 1n !ngular" t0e %ie/ reads model data from t0e

model data from t0e 2scope2scope. o t0e. o t0e 2scope2scope ob3ect is /0ere t0e )ontroller and t0e ie/ s0are data. ob3ect is /0ere t0e )ontroller and t0e ie/ s0are data. !cope is nothing but an object that &lues the View with 'ontroller. They hold the Model !cope is nothing but an object that &lues the View with 'ontroller. They hold the Model data that we need to pass to view. !cope uses Angular(s two)way data binding to bind data that we need to pass to view. !cope uses Angular(s two)way data binding to bind model data to view.

model data to view. *scope is an

*scope is an object that lin"s 'ontroller to the object that lin"s 'ontroller to the View. View. +t is controller(s +t is controller(s responsibility toresponsibility to initiali,e the data that the view needs to display. This is done by ma"ing changes to initiali,e the data that the view needs to display. This is done by ma"ing changes to *scope.

*scope.

ViewModel- A ViewModel is an object that provides specic data and methods to ViewModel- A ViewModel is an object that provides specic data and methods to maintain specic views. /inds view to the model.

maintain specic views. /inds view to the model. Controller

Controller:: +n Angular!0 controller is simply formed by +n Angular!0 controller is simply formed by ava!cript functionsava!cript functions. +t . +t controlscontrols how vi

how view and ew and model will model will communicate.communicate. 'ontrollers'ontrollers are nothing but plain are nothing but plain ava!criptava!cript functions

functions which are which are bound to a bound to a particular particular scope.scope. 'ontrollers should only contain'ontrollers should only contain bindings and logic needed for a single view

bindings and logic needed for a single view.. 'ontroller hand'ontroller handles inputs0 calls theles inputs0 calls the business code and shares data with view via *scope. +n Angula

business code and shares data with view via *scope. +n Angular!0 the business logic isr!0 the business logic is  performed

 performed inside a inside a service service and injectand injected into the ed into the controllercontroller. The contr. The controller uses oller uses thethe serv

services to obtain data and sets it on ices to obtain data and sets it on the *scopthe *scope0 so e0 so it is just aware of it is just aware of the *scopthe *scope ande and not the view.

not the view. -0en a )ontroller is attac0ed to t0e DOM %ia t0e-0en a )ontroller is attac0ed to t0e DOM %ia t0e

ngcontroller

ngcontroller

directi%e, !ngulardirecti%e, !ngular /ill instantiate a ne/ )ontroller ob3ect, using t0e speci4ed )ontroller5s

/ill instantiate a ne/ )ontroller ob3ect, using t0e speci4ed )ontroller5s

constructor function

constructor function

. !. ! ne/

ne/

child scope

child scope

/ill be created and made a%ailable as an in3ectable parameter to t0e/ill be created and made a%ailable as an in3ectable parameter to t0e )ontroller5s constructor function as

)ontroller5s constructor function as

 2scope

 2scope

.. +se controllers to:

+se controllers to:

et up t0e initial state of t0e 2scope ob3ect. et up t0e initial state of t0e 2scope ob3ect.

(2)

!dd be0a%ior to t0e 2scope ob3ect.

Module: A container for the dierent Angular components: controllers, services, factories, lters, directives etc.

De4ning a module:

• ' function'(6 • 5use strict57

88creates a module with the name 'app'

//the empty array is the list of the other modules that app module depends on.

•   angular.module'5app5, 9(7 •

• 88de4ning a module /it0 dependencies

•   angular.module'5anot0er!pp5, 95ng*oute5, 5ngMessages5(7

• ;('(7

+sing a module in t0e HTML:

• <0tml ngapp=>app>? •  

• <80tml?

Module Creation versus Retrieval

88creating a ne/ module 5app5 and o%er/rite any e#isting app module

angular.module'5app5, 9(7

88or, get access to an e#isting app module and de4ne a component

angular.module'5app5(.controller'5Main)ontroller5, Main)ontrollerFn(7

emplates. the template consists of !M", C##, and Angular directives contained in $ust one !M" le

.

templates are w ritten with HTML that contains Angular-specic elements and attributes. Angular combines the template with in!ormation !rom the model and controller to render the dynamic view that a user sees in the browser.

•  Templates" HTML that contains Angular-specic elements and attributes.

o #nline Templates" The HTML that is already the part o! page. •

<di% ngcontroller=>Main)ontroller as mainm>?

<input type=>te#t> ngmodel=>mainm.my@ame> place0older=>Anter Bour

(3)

<p?66mainm.my@ame;; <8p?

<8di%?

•  $%ternal Templates" The HTML that can be !etched !rom the server.

<di% nginclude=>5pat08to8someTemplate.0tml5>?<8di%?

•  #nternal Templates"The script tag containing the template does not need to be included in

the head o! the document& but it must be below the ng-app denition. •

<script type=>te#t8ngtemplate> id=>someTemplate>?

<p?66mainm.my@ame;;<8p?

<8script?

<body?

<di% ngcontroller=>Main)ontroller as mainm>?

<di% nginclude=>5someTemplate5>?<8di%?

<8di%?

<8body?

1ata)binding in Angular apps is the automatic synchroni'ation o! data between the model and view components. The way that Angular implements data-binding lets you treat the model as the single-source-o!-truth in your application. The view is a projection o! the model at all times. -0en t0e model c0anges, t0e %ie/ reCects t0e c0ange, and %ice %ersa. First t0e template '/0ic0 is t0e uncompiled HTML along /it0 any additional mar$up or directi%es( is compiled on t0e bro/ser. T0e compilation step produces a li%e %ie/. !ny c0anges to t0e %ie/ are immediately reCected in t0e model, and any c0anges in t0e model are propagated to t0e %ie/. T0e model is t0e singlesource oftrut0 for t0e application state, greatly simplifying t0e programming model for t0e de%eloper. Bou can t0in$ of t0e %ie/ as simply an instant pro3ection of your model.

1ependency +njection " (roviding the objects that an object needs )its dependencies* instead o! having it construct them itsel!. +se!ul techni,ue !or testing& since it allows dependencies to be moced or stubbed out.

%dentifying &ependencies

A#ample

angular.module'5app5(.controller'5Main)ontroller5, Main)ontrollerFn(7

function Main)ontrollerFn '2rootcope, 20ttp( 6

%ar mainm = t0is7

  mainm.name = 557

  20ttp.get'6met0od: 5&AT5, url: 5abc.com5;(7

  2rootcope.someProp = >omealue>7

(4)

!fter Mini4cation

angular.module'5app5(.controller'5Main)ontroller5, e(7

function e 'a, b( 6

%ar d = t0is7

d.name = 557

b.get'6met0od: 5&AT5, url: 5abc.com5;(7

a.someProp = >omealue>7

;

88Arror: 92in3ector:unpr +n$no/n pro%ider: aPro%ider < a

ecomes impossible for !ngular to detect and in3ect rig0t dependencies.

olutions:

o

2in3ect Property !nnotation:

angular.module'5app5(.controller'5Main)ontroller5, Main)ontrollerFn(7

Main)ontrollerFn.2in3ect = 952rootcope5, 520ttp57

88order in 2in3ect array must matc0 order of parameters

function Main)ontrollerFn '2rootcope, 20ttp( 6

%ar mainm = t0is7

  mainm.name = 557

  20ttp.get'6met0od: 5&AT5, url: 5abc.com5;(7

  2rootcope.someProp = >omealue>7

;

In-line dependencies:

angular.module'5app5(.controller'5Main)ontroller5,

952rootcope5, 520ttp5, Main)ontrollerFn(7

function Main)ontrollerFn '2rootcope, 20ttp( 6

%ar mainm = t0is7

  20ttp.get'6met0od: 5&AT5, url: 5abc.com5;(7

  2rootcope.someProp = >omealue>7

;

(5)

 Angular 2xpressions  JavaScript-lie code snippet //" unit of code that evaluates to a value . 0enotes a binding and tells Angular that it should evaluate an e%pression and insert the result into the 01M in place o! the binding. T0is binding can 0andle continuous updates /0ene%er t0e result of t0e e#pression c0anges.

ngapp directive: T0is directi%e speci4es t0at !ngular s0ould consider 0tml element to be t0e root element o! the app. (hen angular.$s loads for the rst time, it loo)s for the ngapp directive in the !M" page and *ootstrap the app.

+se ngcontroller directi%e to attac0 a controller to t0at particular part of DOM.

'function'(6

  angular.module'5app5, 9(7

  angular.module'5app5(.controller'5&reeting)ontroller5 , &reeting)ontrollerFn(7

function &reeting)ontrollerFn '( 6

%ar greetingm = t0is7

  greetingm.greeting = 5HolaE57 88add a property on t0e c0ild scope

;

;('(7

<di% ngcontroller=>&reeting)ontroller as greetingm>?66 greetingm.greeting ;;<8di%?

ng3epeat - 2epeats a template once per item !rom a collection.

<p ngrepeat=>item in %m.my!rray>?66item;;<8p?

<E o%er Ob3ect?

<p ngrepeat=>'$ey,%al( in %m.myOb3ect>?66%al.property;;<8p?

ng+nit- +nitiali,e the property on scope.

<di% nginit=>%m.someProp = 5%alue goes 0ere5>?

<8di%?

ng'hange- 2valuate the given expression when the user changes the input. <input type=>c0ec$bo#> ngmodel=>%m.con4rmed> ngc0ange=>%m.c0ange'(> 8?

(6)

ng'lic"- !pecify custom behavior when an element is clic"ed.

<button ngclic$=>%m.count = %m.count  G> nginit=>%m.count=>?

  1ncrement

<8button?

count: 66%m.count;;

ng'lass- 1ynamically set '!! classes on an HTML element by databinding an expression

<p ngclass=>5someclass5  5apply5>?Hello !ngular<8p?

<p ngclass=>65my)lassG5: %m.sample.propG, 5my)lassI5: %m.sample.propI,

5my)lassJ5: %m.sample.propJ;>?

Hello !ngular

<8p?

<p ngclass=>6true: 5my)lassG my)lassI5, false: 55;9%m.sample.propG>?Hello

!ngular<8p?

<p ngclass=>65Pending5: 5pendingclass5,

5ubmitted5: 5submittedclass5,

5-aiting5: 5/aitingclass5;9%m.status>?*eser%ation tatus<8p?

ng!how- !hows or hides the given HTML element based on the expression provided to the ng!how attribute

<di% ngs0o/=>%m.s0ould0o/>?<8di%?

ngHide- !hows or hides the given HTML element based on the expression provided to the ngHide attribute

<di% ng0ide=>%m.s0ouldHide>?<8di%?

ng+f - 3emoves or recreates a portion of the 14M tree based on an ng+f expression. HTML

<di% ngif =>%m.s0ouldPresent>?<8di%?

ngHref :

(7)

<a ng0ref =>0ttp:88///.gra%atar.com8a%atar8660as0;; >8?

ngSrc:

<img src=>66%m.pro4lePic+rl;; >8?

<img ngsrc=>66%m.pro4lePic+rl;; >8?

ng)model 1irective- Lins the HTML element and the model. Any changes to the control update the data in your model& and when you change the model it updates the control. T31 3A4 0ATA 5#60#67

*root!cope- 3efers to the app5s root scope #2very app has a single root scope4ther scopes are descendant scopes of the root scope.

88someProp is a%ailable across all t0e components of a module li$e

88controllers, ser%ices, 4lter, directi%es etc.

(8)

er%ices

!ngular ser%ices are substitutable ob3ects t0at are /ired toget0er using dependency in3ection 'D1(.  Bou can use ser%ices to s0are code and data across t0e app.

!ngular ser%ices are:

LaKily instantiated  !ngular er%ices are laKily initialiKed 'initiates only /0en its needed(. !ngular only instantiates a ser%ice /0en an application component depends on it.

ingletons  !ngular er%ices are singletons per !ngular module. Aac0 component dependent on a ser%ice gets a reference to t0e single instance generated by t0e ser%ice factory.

!ngular oers se%eral useful ser%ices 'li$e 20ttp(, but for most applications you5ll also /ant to create your o/n. To use an !ngular ser%ice, you add it as a dependency for t0e component 'controller, ser%ice, 4lter or directi%e( t0at depends on t0e ser%ice. !ngular5s

dependency

in3ection

subsystem ta$es care of t0e rest. T0e service factory function generates t0e single ob3ect or function t0at represents t0e ser%ice to t0e rest of t0e application. T0e ob3ect or function returned by t0e ser%ice is in3ected into any component 'controller, ser%ice, 4lter or directi%e( t0at speci4es a dependency on t0e ser%ice.

!pplication de%elopers are free to de4ne t0eir o/n ser%ices by registering t0e ser%ice5s name and service factory function, /it0 an !ngular module.

881n3ect t0e ser%ice 'not its ob3ect( into t0e

88component 'controller, ser%ice, 4lter, directi%e(

angular.module'5app5(.controller'5Main)ontroller5, Main)ontrollerFn(7

Main)ontrollerFn.2in3ect = 952rootcope5, 520ttp5, 52routeParams5 

function Main)ontrollerFn '2rootcope, 20ttp, 2routeParams( 6

%ar mainm = t0is7

  mainm.name = 557

  20ttp.get'....(7

  2rootcope.someProp = >omealue>7

;

)reating a er%ice or Factory:

angular.module'5app5, 9(7

(9)

angular.module'5app5(.factory'5myFactory5, myFactory(7

function myFactory'( 6

%ar self = 6;, localar7

88add e#posable properties on self 

  self .name = 5T0is is a factory57

return self 7

;

• •

88create a ser%ice

angular.module'5app5(.ser%ice'5myer%ice5, myer%ice(7

function myer%ice'( 6

%ar localar = G7

88add e#posable properties on t0is

t0is.name = 5T0is is a er%ice57

;

angular.module'5app5, 9(7

88)reating a ser%ice /it0 dependencies

angular.module'5app5(.ser%ice'5myer%ice5, myer%ice(7

function myer%ice'20ttp, 2location( 6

88use dependencies 0ere

t0is.name = 5er%ice57

;

881n3ecting t0e ser%ice or factory

angular.module'5app5(.controller'5Main)ontroller5, Main)ontrollerFn(7

function Main)ontrollerFn '2rootcope, 20ttp, myer%ice( 6

%ar mainm = t0is7

  20ttp.get'....(7

  2rootcope.someProp = >omealue>7

  console.log'myer%ice.name(7

;

20ttp: )ommunicate /it0 t0e remote HTTP ser%ers %ia t0e bro/ser5s

NMLHttp*equest ob3ect or %ia "O@P.

20ttp.get'58some+rl5, 9con4g(.t0en'success)allbac$(7

(10)

20ttp.put'58some+rl5, data, 9con4g(.t0en'success)allbac$(7

20ttp.delete'58some+rl5, 9con4g(.t0en'success)allbac$(7

88"O@P request must contain "O@)!LL!) as t0e callbac$ %alue in t0e +*L

20ttp. 3sonp'5///.someot0erdomain.com8some+rl5  5Qcallbac$="O@)!LL!)5,

9con4g(.t0en'success)allbac$(7

con4gOb3 ==? 6

  met0od

: 5&AT5 R 5POT5 R 5P+T5 R 5DALATA5 etc.,

  url

: 58someurl5,

  params

: 5string5 R ob3ect 8SquerytringS8,

  data

: 5string5 R ob3ect 8SpostS8

;

response ==? 6

  data

: 6stringROb3ect;  T0e response body transformed /it0 t0e transform

functions.

  status

: 6number;  HTTP status code of  t0e response.

  0eaders : 6function'90eader@ame(;  Header getter function.

  con4g

: 6Ob3ect;  T0e con4guration ob3ect t0at /as used to generate t0e

request.

  statusTe#t: 6string;  HTTP status te#t of  t0e response.

;

 T0e Promise ob3ect is used for deferred and async0ronous computations.

! Promise represents an operation t0at 0asn5t completed yet, but is e#pected in t0e future. Part of AIG pec no/. Promise on MD@

!ngular promise ser%ice 2q is based on ris o/al5s U

 T0e 20ttp ser%ice is based on t0e deferred8promise !P1s e#posed by t0e 2q ser%ice. !n !ngular ser%ice s0ould be used for delegating HTTP requests and responses.

*outing 0elps you in di%iding your application in logical %ie/s and bind

dierent %ie/s to )ontrollers.

!llo/s to na%igate among t0e %ie/s and also store t0is na%igation in t0e

(11)

P! can still be built /it0out urlbased routing, but as soon as you refres0

t0e page, it /ill land on t0e 4rst %ie/. @o bro/ser bac$for/ard button

support eit0er.

References

Related documents