You are on page 1of 57
UNITY Introduction to Angular and Web Applications Frameworks Syllabus srstanding ng attributes, “Expressions and data Jnoroduction 10 AngulardS, MYC Architecture, Unde pinding, Conditional Directives, Style Directives, Controllers, Filters, Forms, Routers, Modules. Firebase - Docker - Node JS - React - Django - Services; Web Applications Frameworks and Tools - Ul & UX. Contents 7.1 Introduction to AngularJS 7.2. MVC Architecture 7.3. Understanding ng Attributes 7.4 Expressions and Data Binding 7.5 Conditional Directives 7.6 Style Directives Controllers Filters 77 78 79 7.10 Routers Forms 7.11 Modules 7.12 Services 7.13. Web Applications Frameworks and Tools 7.14 rks Questions with Answers Two Mar nt WED Anptioation we) aacanl IS Fromewoyas. Introduction to AngulanlS ® Aggatars is a powertel Javaseny framework # isan open snare flontend enables wed application framework, © Tis tioensead mnder Apache Hisense Version 2.0. © Weatends HTML DOM with additional ataibates, It is more responsive 10 User actions, Advantages. Following are the advantages of AngulalS, 1. Built by Google Engineers : The AngularlS is maintained by dedieated Google Enginocrs, That means = There is huge community tor development and enhancement, 2 MVC Support + It is based on Model View Controller (MYC) architecture whieh provides cpatation of model, view and controller components, 3. Intuitive = 1 is more intuitive as it makes use of HTML as a declarative language, Moreover, it is less britile for reorganizing, : 4. Comprehensive: AngularlS isa comprehensive solution for rapid frontend development, Ut does not need any other plugins or framewor 8 Rich Features : There is a wide range of features supported by AngulardS such as data binding, dependency injection, enterprise level testing and so on, 6. Unit Testing : The Angularl code is unit testable, 7. Reusable Code: Angular) support for using the reusable components, 8 Less Code + It support for less code anit more flnetionality, Disadvantages 1. As AngutardS is based on JavaScript framework, it is not secur 2. There are multiple ways to do the sume thing with Angulaid, Sometimes, it can bo hard for novices to say whieh way is better for a task, Foaturos of AngularJS ‘There are core fetures Angula3S hare widely us by el 1, Data binding + I allows the 4 components, b developers, ‘These are - "wlomitie synchronization between model and vie 2, Seape : There ore some objec i og and Hom model that cun bo correlated! controller HM view, ‘TMenNICM. PUBLICATIONS A Up AOE OF bo wlago upp Technotostios ues Introduction to Angular and Web Applications Frameworks 3, Controller + These are busivally JavaScript functions that are bound to particular scope. 4. Directives The directives is de Filter ‘gned to give ITTML new functionality. This feature allows to select subset from array of items. fh, Routing : This feature allows to switch between multiple views. 7, Services : There is a support for many built in services for Angular] 8. Dependency injection ¢ ICis a sotlware design pattern that helps the developer to develop and understand the application easily. FAA Me Architecture Concopt of MVC The MVC stands for model, view and controller, TC is a patter for the architectural framework, It consists of three parts tion data, ‘This module responds to the request made from view, The model gives instructions to controller to update when the respons 1. Modet ¢ ‘This part of the architecture is responsible for managing the applica is made, 2. View : This part takes care of the preser ation of data, ‘The data is presented in desired pt based system using ISP, ASP, PHP and so format with the help of view, This isa s on, 3. Controller : The controller receives input, validates it, and then performs: business operations that modify the state of the dau model. The contr Her ba: squest and performs interaction with madel, Refer Fig. 7.2.1 cally responds to Fig, 7.2.1 MVG architacture MVC in AngulardS © Modules itt AnguluedS serve as containers 10 help you organize your application into logical units, + Modutey toll Angulard$ how an application is configured. TECHNICAL PULLICA TIONS san apyttuurat Ror owt Introduction to Angular and Web Applications Frame; Yieb Technologies 7-4 orks * In angularJS the module are represented using the directive and module name. + The scope object binds the view with controller. in AngularJS it is possible to have multiple views for single page application. + The ng-view and ng-template and ng-route directives support the concept of views. * The use of controller in Angular}S is to control the flow of data. The ng-controller directive is used for this purpose. Refer Fig. 7.2.2. Module EDK mam Directive Services Fig. 7.2.2 MVC with angularJS 1. Explain the MVC architecture of AngularIS Understanding ng Attributes * In AngularJS, the capacity of HTML is extended using the ng-directives. * The directives are specified with ng prefix, * The three commonly used ng-directives are 1. mgrapp : Ths directive defines an Angular! application 2. ngrmodel : This directive binds the value of HTML controls to application 43% These controls can be input, select, textarea and so on, 3. ng-hind : This directive binds application data to HTML view. Let us now Icam and understand how to develop Angular JS application. TECHHICAL PUBLICATIONS? «on upinay or knowlodgo Web Technologies 7-5 Introduction to Angular and Web Applications Frameworks Step 1: Create an AngularJS code as follows in a Notepad, Save it using the extension htm or html i AngularJS Document{FirstApp.html] | ; | f } My First AngularJS Application i

AngularJS Application

Enter your Name:

Welcome Output My First Angular’ XE | AngularJS Application ee el | | Welcome MrX¥Z € © file:///c:/FirstApp.htm! Enter your Name: Script Explanation : 1. The AngulardS script is written within tags. The AngualarIS is based on JavaScript framework. The framework for Angular}S is loaded using the tag, Tt is as follows - TECHNICAL PUBLICATIONS® - an up-thrust for knowledge ad Wed Applications Frameworks OS ve nmanp dincetive is defined in above script as follows « 2. Detining np-app directive : The mpsopp dinetive IES ae Ente: your Name.

4. Defining np-bind : We can bind the value entered in the textbox with name using np- bind directive.

Welcome | “0 Up oni be brredege vob Technologies 7-7 Introduction to Angular and Web Applications Frameworks Output t HESS OK JasDirectiveDen XE : € O file///d:/DirectiveDemc ec» = I love my country!!! ' | | | | | | | | | | ES 3. ng-model : The ng-model directive binds the value of HTML control to application data. These controls can be input, select, textarea and so on, For example - AngularJS Document[FirstApp.html] My First AngularJS Application

The elements are -

  • , TECHNICAL PUBLICATIONS® 8 thal erimmsany ag Web Technologies 7-9 Introduction to Angular and Web Applications Frameworks Output PéDirectiveRep XE €_ © file:///d:/DirectiveRepes « = The elements are - 10 +20 30 = 40 | | | | | Expressions and Data Binding © In AngularJS the expressions are written within {{ }}. For example - {{2 + 3}} is expression. AngularJS binds data to HTML using expressions. m the result of evaluation. © AngularJS solves the expression and retuy far to JavaScript expressions. The expression © The expressions in AngularJS are just simil contains literals, variables and operators. AngularJS Document[ExpressionDemo.html] old = true’> Thee checks i wut checked yop Technologies 7-19 Introduction to Angular and Web Applications Frameworks Script Explanation ; In above script, 1) We have used ng-if element for the input checkbox. This checkbox is defined by myld. 2) If the checkbox is checked then the welcome message will be displayed else, the “gheckbox is not checked” message will be displayed. For such conditions the ng-if directive is used. 2, The ng-switch Directive The ng-switch directive allows the user to select the desired HTML element depending upon the expression. Child elements with the ng-switch-when directive will be displayed if it gets a match, otherwise the element and its children will be removed. syntax "value"> "value"> Select the desired brand: ste> Sdiv ug-switeh="myld'> div ng-swatch-whens'Samsung’> Sh3>You have chosen the Samsung TECHNICAL PUBLICATIONS® - an up-thrust for knowledge list, io which various mobile brands are listed out. The of 2 maich with the selected mobile brand, When a user selects 2 eS ae eer prima tor eetedge \yeb Technologies 7-15 Introduction to Angular and Web Applications Frameworks [BA Style Directives The ng-style directive is used to set the style for the HTML elements. The value assigned to the ng-style must be the object or an expression returning the object. Inside this object the CSS propertics and values are given as key-value pairs. syntax ‘myApp" ng-controller="myCtl"> East or West India is the BESTI! var app = angular.module("myApp’, [); app.controller(‘myCtrl’, function(Sscope) { Sscope.myStyle = { color’: "black’, . “packground.color" : “kbaka’, “sfont-size® :*20px", yh 1D | DB siledemanemt © File | E/engular_Estye.. | [East o1 ‘West India is the BEST!!! TECHNICAL PUBLICATIONS® - an up-thrust for knowledge Pe0IReONS Freeney, remo Ay TE sz oszg color, background =] the flow of daz The ng-controller act connsicing properdes 2nd fimetions. hich refers to the application/module that Geined vib properis. These properties are then assigned with some by following exemple - Angule JS Dosument|ContollerDemo html] < 3 aa 4 gman Soe Tap. span posers oom ejen ths eagalarje/1.3 W/engulas min js'> User TECHNICAL PUBLICATIONS® - an up-hnust for knowiedga lett Adéress: AAA lives in city Pune | I i | Cav: Pune | | | { j Script Explanation : In sbove seript : 1, The two propenies user and city are defined. Along with them, @ ™ Address function() is invoked, 2. This function returns the sting containing values to the properties 3, This function is then bounded to HTML, Controller with external File We can write and save the contolle in some extemal file, This file can be tC? the HTML document. Hee isthe illustration TEOHOUCAL PUBLICATIONS. an pt ar hnowed® ethor aed invored Web Technologies 7-19 Introduction to Angular and Web Applications Frameworks Step 1: Create a file in Notepad. Name it with extension js. External File[MyController.js] angular.module('MyApp’, {]). controller('MyController’, function($scope) { $scope.user = "AAA"; $scope.city = "Pune’ Sscope.address_fun function() { retum $scope.user+" "+$scope.city; } yi Step 2 : Create a HTML document invoking the external js file created in above step. HTML Document{ControllerFileDemo.html]
    \ser">

    jty">
    User: Output ie : ESE OG bx CSE € © file///d:/Contro!! e » = User: TECHNICAL PUBLICATIONS® - an up-thrus for knowledge 1.10 __hracton to Arglr and Wob AppcationsFremonerg Wb Techinologios _ Roview Question Tata ems of contain AnguardS 2 Explain it with the help of an exampre, ab a . Filters + Filters are used to modify the data, «These are used along with expressions or directives using pipe (|) character, + Commonly used filters are - = Purpose uppercase Convers the texto uppercase | lowercase Convers the text to lower case, currency ‘Converts the number into currency format. | orderBy Arranges the elements of the array based on criteria, | filer Selects the subset of tems from array. 1. Example Demonstrating uppercase filter AngularJS Document{FilterDemo1 html] f mgt c= aps ter Veja areageapis coralajaxMbo/angularjo/ 3.14/angular.min.js'> po Sih ng-comaraller: MyControlier > apo Tue { wppetcase }}

    Alar coerigne anggules a 7 ANomtaces yCennrotl function($ucope) { ee ee a Web Technologies 7-20 Introduction to Angular and Web Applications Frame Output i So Orne X <|x +v | © @ file:///a:yritterd ec» =] The name is AAA i | { | a 2. Example Demonstrating lowercase Filter AngularJS Document[FilterDemo2.html]

    The name is {{ user | lowercase }}

    Wob Tochnology 1-2 _hcon hed on 0D hop tcatens Frama outpot ay he, €&_ @ thepfetfiner : ‘The name is aaa 3, Example Domonstrating currency Filtor AngularsS Document{FilterDemo3.htmnl] crip s1e="hutpa//ajax oogloapi.com/ajex/ibs/angulara/1.3.14/anyuar. min,js">
    <
    ‘angular.nodile(’MyA pp’ {I} controll MyControllr, function(Sscope) { $scope.amount = 100 yh TECHNICAL PUBLICATIONS® - an vpinst for nowiedg® Web Technologies 7-23 Introduction to Angular and Web Applications Fra. Output pean eleva < EX + | & © filey//dyFiterd: c» = The amount is $100.00 } 4, Example Demonstrating filter Filter AngularJS Document[FilterDemo4.html]
    © pate] > bY € © file///a:/FilterDeme4 cc. = ; ‘The cities having character typed in textbox are - (eae + Mumbai i + Chennai + Surat Kolkatta Dehradun 5. Example Demonstrating orderBy Filter AngularJS Document[FilterDemo5.html] isbody>
    angular Sevope persoaia tale(MyApp, iy] contraler(yControlr,function(Sscope) { ‘The names are listed in ascending order of city name \ f © BBB lives in Banglore | * CCC lives in Chennai | « DDD lives in Delhi ¢ EEE lives in Mumbai © AAA lives in Pone J Web Technologies “7-27 Introduction to Angular and Web Applications Frameworks Forms ; Form is a collection of various controls. © AngularJS support two types of controls - Data binding and validation controls. * Various controls supported by AngularJS forms are - o Input © Select o Button o textarea. 4. Input Control User can type some text in the text box and the same text can be displayed on the AngularJS document. For this binding we use inside the
    tag. Input Control Demo cht ncophon= wbind' > When vou cheat the checkbox ths memage will be displayed aier> s sefis> Outpet P sro x eitheio ae © 0 hevjeKresge: e» Bf Check the checiebor Z Wher you check the checkbor thi i Meyrin this message will Web Technologies _ and Wab Applications Framewor. 3. Radio Button The radio button is basically a group of buttons which allows you to choos time. one value at Let us sce an illustrative script that uses Radio button control AngularJS Document[RadioButtonDemo.htmi] 'http://ajax. googleapis.com/ajax/libs/angularjs/1.3. 14/angular. min.jg"> Select the color:
    Red
    Green "radio" ng-model="color’ valu >Bluo

    You have chosen Green Color

    You have chosen Blue Color

    Output fevtasobet x oF e MW € O fhepjaRaaobuns Select the color Red, Green, Blue You have chosen Bluc Color Al, PUBLICATIONS® - an up-tnust for knawiedgo AR InP AWW SN HED BMAINNG 6 Reg DW Aeieaner We se aNd ATS SRI a HA WD Be SANE MaRtto is taken fy Say aad Daten SNS DAT BAS DRERIS the peaks Gnane 8 AO HEME doormen, the ag. AA RARE RAE IES. GORE ELOY, & Ye aS MON BE Ne WE HAs Ginnwie & Re ant Show NEML soations qrnniling WOOT ATG ATO NRIs Whos AOwAT oF MVE Radio Netto is. ay IRHDNG TNE ARNT Sagan’ SRW Tek DA IAEA DERN TD SSNIND SOT BGS, Bar enarnypte + AQUI DanmanQekeom Ng] ROU san Same s a TERA AAR AGATA EATEN A ARS SSey SEINE Sees AS Nasi PARAS : Seeman cater naa SN SANEU Vale WORD SES I See Steen SAA REARS Naivangewash ahaa SO) You have choses Rad Cae Cys SAND gwerewheas ys sp> Vou have chosen Graca Daler

    we Sa swatch when's ~p> You nave chosen Bino Calas Sys saw ~Aiv> Sly ee ——— TEORIEAL PUSUCANONSS ae San hasty ee Wed Teabags otootatinn ) Anger ant Hed dono Framwenrast Outpar Qe sh SelentBoa Ne « Select the calor [Sreen You have chosen Given Color & The button We ean create a button contial and invoke some Ainetionality at its ched event Boe examples AngulandS Document{ButtonDemo,htmnl] Aims Ssoupt sie & TAU SU/eAIAN GooMea HS oomLaLAchDs/angnlays’ Tg. LVangular mis jes eA HOS Sbatys Saiv nosapp © “MYA nar contioltor -"MyConttoller > Stonn> Speknter your Name: 59> storm Xp>Welcoma {{uisemame}} sitive Sscript> var app = angular module’ My APD’ I: —app.contioller’ MyControttor’ fmetion(Sseope) { Sscope namo = “AAA i Sscope.dinplay =funrction0 { Sacope asemamenSscope namo, k » S/seript> sdoumt> TECHAGAL PUBLICATIONS = an thst hy Rnowes9> bh ae Teorey Weer XYZ dp aoe SAR on MESTRA creat he Garston Aphay Biel named dy dowsing notion displays ingen gent dn. + ThengRontemaklehay + Single page application & a wed spplient @ The ngRoute module prniges a. TuteProvider: # Rass camps ef rredag ¢ Rhy in wed again, ety te the prowess of penetts 2 be dighayad Nasal on URL, For instance, solving She ame page and if dhe usr clicks on the Sammy de asd pee seamet ay demon tea, wedange otis infimeton is digglayed brmadiately on the Se HOS your aqication t anaw a single page application, a that opotss within a single WD PEE Whon a usr intomets with the page instead of the oatire page reloading, oaly the REESSEY puts of he PAE EY aNd sAMehomasly, This improves: over! owed spplicadion aAd rahi the ammuat of data that neads t0 6 mranaitaad over dhe nsw patie 0 ‘The neRonte module roetes your eaicaton to diflerant pages without reloading the The StoanProvider eases see usd ty map the particular view with comespondling ATL page ening templarn, oe $10 seniog, which allows developers © define mutes and asswiatal views for thar application, The nia sie Typically dofinad in the apptication's configuration phase. TRRAKCAL RRLICATONG an era br onwme Wed Techaodgins TS fetrodkcton to Angutar and Wed Anotestons Framennrts. * The routes are defined by calling the when method on the routeProvider object. JWssing tn a puth (siting oF regen) and a configuration object that specifies the template and coamuller to use the the route. The templeURL is used to whieh the URL of the routal page is spevitiad, 5 + The ngRoute module routes your application to different pages without reloading the entire application, I is used tn angularmodule, Demo Application Step ts Create the main page for invoking the view pages, AngularJS Document{ViowDemo.htmi] SDOCTYPS huts PS//AIAN GOEMOUPIL.© aan bbs angulans’) UML angubar mun gs SS /seryey script Stes RIPS AN GON TRNSS CO AUT ARTA LA HA AMMAE TOUTE JST S'S apts boty agape nyApy > cpr sa tretst@yY SMa as Sp Sa brete"@ wit SFist Views a> Str Sa bref" # view?" >Sorond View SAT SDS Sav ng-vew> < ate var app = angular.mostule(my App PagRoute’)s app. configihmenionSroutePronder) { SrouteProwder ewer", { templatelit “‘ViewDento ‘unt y awheng iow { yemplateUr Mew Lbonl » Awhen( view?" { ateUrd View 2 bun!” temp! ww } Jecrpt> JECRARCAL PUBLICA TONS® «a9 agp ent Re tnt San rene, ‘Blow 2 Creote vaew ! Aa page to deeply frst view = 7-95 Introduction to Angular and Web Applications Framaworks Wob Technologies On clicking the first view or second view hyperlink the corresponding page will be displayed. Thus routing to different views is possible using ng-route. [ 1. Write an AngularJS application to demonstrate the concept of router. = Modules i We can write the script in AngularJS using different modules. Basically the modules help in separation of logic such as controller, service. application etc. * The modules can be defined in separate .js fil Application module and controller module. * Most commonly there are two modules in AngularJS with the help of example. * Let us understand how to use modulk # First consider the following code without module ~ i AngularJS Document shimt> gular minis
    sss typ TECHEAL TYOLICATIONS® eeu Rant Ay Aalede Web Technol jologies 7-37 Introduction to Angular and Web Applications Frameworks City: Step 4: The output can be viewed as Jd:/ModuleDe. Xe € © file///a:/ModuleDer ¢ >» EJ Services “Phe servives are functions or objeets that are intended to carry out specific task, In AngulardS there are 30 builtin services used to carry out variety of tasks, Bullt-In Services Lot us understand the use of services with the help of examples + 1. ‘The Shtp Service “This is» commonly used service in AngulaedS. By using this serviee, the request ean be inde to the server tnd the apptication handles the response, Stop 1: Create a simple web documentas follows + mnsplntntl Well Donett! TECTARGAL PUGLIGATIONS® an up-tuaT ar hnotedgo ston to Angular and Web Applications Fra IMOWOrks, Step 2: Now erate web dosumnt shat will make use of SHlp service fo get the message stored in above htm! file and to display the canter AngularJS Document[ServiceDemot.html] .s'angulags/1.3. W/angulat.min js"> Out + is Q x < nSevide e» = Mesege cheered foe a fle ig Well Done!!! | | Riza | Wob Tochnologios 7-39 Introduction to Angular and Web Applications Framework 2. The $timeout Service The Stimeout service is useful to execute certain task after some time interval. Following example displays one message on the browser and after 5 seconds another message will be displayed. AngularJS Document[ServiceDemo2.html]

    : Output c oa < ISDS i ef ffdySeric ¢ 2.5 Message will be changed after 5 seconds “Welcome User TECHNICAL PUSLICATIONSS «20 mst fy ote 1d Web Aopications Frame ERE Aoernons Fromeworks = GB x € c » & Message will be changes after 5 seconds ° Good Bye!!! ‘Creation of Custom Service Bs powsihie te crate our oun seve: The Sovioe is normally created using two sactheds > Lo Rome) 2 Service sng faces seta’ wr ce defines fisted he method that performs specific Sar) sani Seep 2: Lamy secs ential we oa deine he serie anda method is then assigned 10 erence ‘Web Technologios 7-41 Introduction to Angular and Web Applications Frameworks Step 3: Then a controller is defined and the scope object and service method is invoked in it. App.controller(MyController, function(Sscope, CalculateService) ( $scope.add = function() { Sscope.result = CalculateService.add(Sscope number1 Sscope.number2); } we The above three steps must be applied within the

    Addition of two numbers

    Enter first number:

    Enter second number:

    You might also like