AngularJS - Luzala

Transcription

I

AngularJSAbout the TutorialAngularJS is a very powerful JavaScript library. It is used in Single Page Application(SPA) projects. It extends HTML DOM with additional attributes and makes it moreresponsive to user actions. AngularJS is open source, completely free, and used bythousands of developers around the world. It is licensed under the Apache licenseversion 2.0.AudienceThis tutorial is designed for software professionals who want to learn the basics ofAngularJS and its programming concepts in simple and easy steps. It describes thecomponents of AngularJS with suitable examples.PrerequisitesYou should have a basic understanding of JavaScript and any text editor. As we aregoing to develop web-based applications using AngularJS, it will be good if you havean understanding of other web technologies such as HTML, CSS, AJAX, etc.Disclaimer & Copyright Copyright 2014 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of TutorialsPoint (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,distribute or republish any contents or a part of contents of this e-book in anymanner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and asprecisely as possible, however, the contents may contain inaccuracies or errors.Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timelinessor completeness of our website or its contents including this tutorial. If you discoverany errors on our website or in this tutorial, please notify us atcontact@tutorialspoint.comi

AngularJSTable of ContentsAbout the Tutorial ·······iAudience isites ···············iDisclaimer & �····iTable of Contents ··········· 1General Features ········1Core Features ·············1Concepts s of AngularJS ntages of AngularJS ·················4AngularJS Directives · 53.MVC ARCHITECTURE ······· 9The Model ················10The View ··················10The Controller ··········104.FIRST �············· 11Creating AngularJS Application ·········11Executing AngularJS Application ·······11How AngularJS Integrates with HTML 5.DIRECTIVES ···················· 14ng-app directive ·······14ng-init directive ········14ng-model directive ···15ii

AngularJSng-repeat directive ···156.EXPRESSIONS ················· 177.CONTROLLERS ··············· 198.FILTERS · 22Uppercase Filter ·······22Lowercase Filter ·······22Currency Filter ··············23OrderBy ··············239.TABLES · 2710. HTML �····················· 31ng-disabled �····31ng-show Directive ····31ng-hide Directive ······31ng-click Directive ······3211. MODULES ······················ 34Application Module ··34Controller Module ····34Use Modules ············3512. FORMS · 39Events lick te Data ···········4013. INCLUDES ······················ 4414. AJAX ····· 48iii

AngularJS15. VIEWS ··· 52ng-view Directive ·····52ng-template Directive ·······················52 routeProvider Service ······················5316. SCOPES · 57Scope �··········5717. SERVICES ······················· 61Using Factory Method ing Service Method . DEPENDENCY INJECTION ························ 64Value Factory e er ··················6719. DIRECTIVES ···················· 70ng-app directive ·······70ng-init directive ········70ng-model directive ···71ng-repeat directive ···7120. INTERNALIZATION ········· 73Example Using Danish Locale ············73Example Using Browser Locale ··········74iv

1. OVERVIEWAngularJS is an open-source web application framework. It was originally developedin 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Itslatest version is 1.2.21.Definition of AngularJS as put by its official documentation is as follows:AngularJS is a structural framework for dynamic web applications. It lets youuse HTML as your template language and lets you extend HTML's syntax toexpress your application components clearly and succinctly. Its data bindingand dependency injection eliminate much of the code you currently have towrite. And it all happens within the browser, making it an ideal partner withany server technology.General FeaturesThe general features of AngularJS are as follows: AngularJS is a efficient framework that can create Rich Internet Applications(RIA). AngularJS provides developers an options to write client side applicationsusing JavaScript in a clean Model View Controller (MVC) way. Applications written in AngularJS are cross-browser compliant. AngularJSautomatically handles JavaScript code suitable for each browser. AngularJS is open source, completely free, and used by thousands ofdevelopers around the world. It is licensed under the Apache license version2.0.Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain web applications.Core FeaturesThe core features of AngularJS are as follows: Data-binding: It is the automatic synchronization of data between model andview components. Scope: These are objects that refer to the model. They act as a glue betweencontroller and view.1

Angular JS Controller: These are JavaScript functions bound to a particular scope. Services: AngularJS comes with several built-in services such as http tomake a XMLHttpRequests. These are singleton objects which are instantiatedonly once in app. Filters: These select a subset of items from an array and returns a new array. Directives: Directives are markers on DOM elements such as elements,attributes, css, and more. These can be used to create custom HTML tags thatserve as new, custom widgets. AngularJS has built-in directives such asngBind, ngModel, etc. Templates: These are the rendered view with information from the controllerand model. These can be a single file (such as index.html) or multiple viewsin one page using partials. Routing: It is concept of switching views. Model View Whatever: MVW is a design pattern for dividing an applicationinto different parts called Model, View, and Controller, each with distinctresponsibilities. AngularJS does not implement MVC in the traditional sense,but rather something closer to MVVM (Model-View-ViewModel). The AngularJS team refers it humorously as Model View Whatever. Deep Linking: Deep linking allows to encode the state of application in theURL so that it can be bookmarked. The application can then be restored fromthe URL to the same state. Dependency Injection: AngularJS has a built-in dependency injectionsubsystem that helps the developer to create, understand, and test theapplications easily.ConceptsThe following diagram depicts some important parts of AngularJS which we willdiscuss in detail in the subsequent chapters.2

Angular JSAdvantages of AngularJSThe advantages of AngularJS are: It provides the capability to create Single Page Application in a very clean andmaintainable way. It provides data binding capability to HTML. Thus, it gives user a rich andresponsive experience. AngularJS code is unit testable. AngularJS uses dependency injection and make use of separation of concerns. AngularJS provides reusable components. With AngularJS, the developers can achieve more functionality with shortcode. In AngularJS, views are pure html pages, and controllers written in JavaScriptdo the business processing.3

Angular JSOn the top of everything, AngularJS applications can run on all major browsers andsmart phones, including Android and iOS based phones/tablets.Disadvantages of AngularJSThough AngularJS comes with a lot of merits, here are some points of concern: Not secure : Being JavaScript only framework, application written inAngularJS are not safe. Server side authentication and authorization is mustto keep an application secure. Not degradable: If the user of your application disables JavaScript, thennothing would be visible, except the basic page.AngularJS DirectivesThe AngularJS framework can be divided into three major parts: ng-app : This directive defines and links an AngularJS application to HTML. ng-model : This directive binds the values of AngularJS application data toHTML input controls. ng-bind : This directive binds the AngularJS application data to HTML tags.4

2. ENVIRONMENTAngular JSThis chapter describes how to set up AngularJS library to be used in web applicationdevelopment. It also briefly describes the directory structure and its contents.When you open the link https://angularjs.org/, you will see there are two options todownload AngularJS library: View on GitHub – By clicking on this button, you are diverted to GitHub andget all the latest scripts. Download – By clicking on this button, a screen you get to see a dialog boxshown as:5

Angular JSThis screen offers various options for selecting Angular JS as follows: Downloading and hosting files locallyoThere are two different options : Legacy and Latest. The namesthemselves are self-descriptive. The Legacy has version less than 1.2.xand the Latest come with version 1.3.x.oWe can also go with the minimized, uncompressed, or zipped version.CDN access: You also have access to a CDN. The CDN gives you access toregional data centers. In this case, the Google host. The CDN transfers theresponsibility of hosting files from your own servers to a series of externalones. It also offers an advantage that if the visitor of your web page hasalready downloaded a copy of AngularJS from the same CDN, there is no needto re-download it.We are using the CDN versions of the library throughout this tutorial.ExampleNow let us write a simple example using AngularJS library. Let us create an HTMLfile myfirstexample.html shown as below: !doctype html html head script src .3.0beta.17/angular.min.js" /script /head body ng-app "myapp" div ng-controller "HelloController" h2 Welcome {{helloTo.title}} to the world of Tutorialspoint! /h2 /div script angular.module("myapp", []).controller("HelloController", function( scope) { scope.helloTo {}; scope.helloTo.title "AngularJS";}); /script /body /html 6

Angular JSLet us go through the above code in detail:Include AngularJSWe include the AngularJS JavaScript file in the HTML page so that we can use it: head scriptsrc 2.15/angular.min.js" /script /head You can check the latest version of AngularJS on its official website.Point to AngularJS appNext, it is required to tell which part of HTML contains the AngularJS app. You cando this by adding the ng-app attribute to the root HTML element of the AngularJSapp. You can either add it to the html element or the body element as shown below: body ng-app "myapp" /body ViewThe view is this part: div ng-controller "HelloController" h2 Welcome {{helloTo.title}} to the world of Tutorialspoint! /h2 /div ng-controller tells AngularJS which controller to use with this view. helloTo.title tellsAngularJS to write the model value named helloTo.title in HTML at this location.ControllerThe controller part is: script angular.module("myapp", []).controller("HelloController", function( scope) { scope.helloTo {}; scope.helloTo.title "AngularJS";});7

Angular JS /script This code registers a controller function named HelloController in the angular modulenamed myapp. We will study more about modules and controllers in their respectivechapters. The controller function is registered in angular via theangular.module(.).controller(.) function call.The scope parameter model is passed to the controller function. The controllerfunction adds a helloTo JavaScript object, and in that object it adds a title field.ExecutionSave the above code as myfirstexample.html and open it in any browser. You get tosee the following output:What happens when the page is loaded in the browser ? Let us see: HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded, the angular global object is created. The JavaScript which registers controller functions is executed. Next, AngularJS scans through the HTML to search for AngularJS apps as wellas views. Once the view is located, it connects that view to the corresponding controllerfunction. Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by thecontroller. The page is now ready.8

3. MVC ARCHITECTUREAngular JSModel View Controller or MVC as it is popularly called, is a software design patternfor developing web applications. A Model View Controller pattern is made up of thefollowing three parts: Model - It is the lowest level of the pattern responsible for maintaining data. View - It is responsible for displaying all or a portion of the data to the user. Controller - It is a software Code that controls the interactions between theModel and View.MVC is popular because it isolates the application logic from the user interface layerand supports separation of concerns. The controller receives all requests for theapplication and then works with the model to prepare any data needed by the view.The view then uses the data prepared by the controller to generate a finalpresentable response. The MVC abstraction can be graphically represented asfollows.9

Angular JSThe ModelThe model is responsible for managing application data. It responds to the requestfrom view and to the instructions from controller to update itself.The ViewA presentation of data in a particular format, triggered by the controller's decisionto present the data. They are script-based template systems such as JSP, ASP, PHPand very easy to integrate with AJAX technology.The ControllerThe controller responds to user input and performs interactions on the data modelobjects. The controller receives input, validates it, and then performs businessoperations that modify the state of the data model.AngularJS is a MVC based framework. In the coming chapters, we will see howAngularJS uses MVC methodology.10

4. FIRST APPLICATIONAngular JSBefore creating actual Hello World ! application using AngularJS, let us see the partsof a AngularJS application. An AngularJS application consists of following threeimportant parts: ng-app : This directive defines and links an AngularJS application to HTML. ng-model : This directive binds the values of AngularJS application data toHTML input controls. ng-bind : This directive binds the AngularJS Application data to HTML tags.Creating AngularJS ApplicationStep 1: Load frameworkBeing a pure JavaScript framework, it can be added using Script tag. scriptsrc 2.15/angular.min.js" /script Step 2: Define AngularJS application using ng-app directive. div ng-app "" . /div Step 3: Define a model name using ng-model directive. p Enter your Name: input type "text" ng-model "name" /p Step 4: Bind the value of above model defined using ng-bind directive. p Hello span ng-bind "name" /span ! /p Executing AngularJS ApplicationUse the above-mentioned three steps in an HTML page.11

Angular JStestAngularJS.htm html title AngularJS First Application /title body h1 Sample Application /h1 div ng-app "" p Enter your Name: input type "text" ng-model "name" /p p Hello span ng-bind "name" /span ! /p /div scriptsrc 2.15/angular.min.js" /script /body /html OutputOpen the file testAngularJS.htm in a web browser. Enter your name and see theresult.12

Angular JSHow AngularJS Integrates with HTML The ng-app directive indicates the start of AngularJS application. The ng-model directive creates a model variable named name, which can beused with the HTML page and within the div having ng-app directive. The ng-bind then uses the name model to be displayed in the HTML span tag whenever user enters input in the text box. Closing /div tag indicates the end of AngularJS application.13

5. DIRECTIVESAngular JSAngularJS directives are used to extend HTML. They are special attributes startingwith ng-prefix. Let us discuss the following directives: ng-app - This directive starts an AngularJS Application. ng-init - This directive initializes application data. ng-model - This directive defines the model that is variable to be used inAngularJS. ng-repeat - This directive repeats HTML elements for each item in acollection.ng-app directiveThe ng-app directive starts an AngularJS Application. It defines the root element. Itautomatically initializes or bootstraps the application when the web page containingAngularJS Application is loaded. It is also used to load various AngularJS modules inAngularJS Application. In the following example, we define a default AngularJSapplication using ng-app attribute of a div element. div ng-app "" . /div ng-init directiveThe ng-init directive initializes an AngularJS Application data. It is used to assignvalues to the variables. In the following example, we initialize an array of countries.We use JSON syntax to define the array of countries. div ng-app "" ng-init "countries [{locale:'en-US',name:'United States'},{locale:'en-GB',name:'United Kingdom'},{locale:'en-FR',name:'France'}]" . /div 14

Angular JSng-model directiveThe ng-model directive defines the model/variable to be used in AngularJSApplication. In the following example, we define a model named name. div ng-app "" . p Enter your Name: input type "text" ng-model "name" /p /div ng-repeat directiveThe ng-repeat directive repeats HTML elements for each item in a collection. In thefollowing example, we iterate over the array of countries. div ng-app "" . p List of Countries with locale: /p ol li ng-repeat "country in countries" {{ 'Country: ' country.name ', Locale: ' country.locale }} /li /ol /div ExampleThe following example shows the use of all the above-mentioned directives.testAngularJS.htm html title AngularJS Directives /title body h1 Sample Application /h1 div ng-app "" ng-init "countries [{locale:'en-US',name:'United States'},{locale:'en-GB',name:'United Kingdom'},{locale:'en-FR',name:'France'}]" p Enter your Name: input type "text" ng-model "name" /p 15

Angular JS p Hello span ng-bind "name" /span ! /p p List of Countries with locale: /p ol li ng-repeat "country in countries" {{ 'Country: ' country.name ', Locale: ' country.locale }} /li /ol /div scriptsrc 2.15/angular.min.js" /script /body /html OutputOpen the file testAngularJS.htm in a web browser. Enter your name and see theresult.16

6. EXPRESSIONSAngular JSExpressions are used to bind application data to HTML. Expressions are written insidedouble curly braces such as in {{ expression}}. Expressions behave similar to ngbind directives. AngularJS expressions are pure JavaScript expressions and outputthe data where they are used.Using numbers p Expense on Books : {{cost * quantity}} Rs /p Using String p Hello {{student.firstname " " student.lastname}}! /p Using Object p Roll No: {{student.rollno}} /p Using Array p Marks(Math): {{marks[3]}} /p ExampleThe following example shows the use of all the above-mentioned expressions:testAngularJS.htm html title AngularJS Expressions /title body h1 Sample Application /h1 div ng-app "" ng-init "quantity 1;cost 30;student };marks [80,90,75,73,60]" p Hello {{student.firstname " " student.lastname}}! /p p Expense on Books : {{cost * quantity}} Rs /p p Roll No: {{student.rollno}} /p p Marks(Math): {{marks[3]}} /p 17

Angular JS /div scriptsrc 2.15/angular.min.js" /script /body /html OutputOpen the file testAngularJS.htm in a web browser and see the result.18

7. CONTROLLERSAngular JSAngularJS application mainly relies on controllers to control the flow of data in theapplication. A controller is defined using ng-controller directive. A controller is aJavaScript object that contains attributes/properties, and functions. Each controlleraccepts scope as a parameter, which refers to the application/module that thecontroller needs to handle. div ng-app "" ng-controller "studentController" . /div Here, we declare a controller named studentController, using the ng-controllerdirective. We define it as follows: script function studentController( scope) { scope.student {firstName: "Mahesh",lastName: "Parashar",fullName: function() {var studentObject;studentObject scope.student;return studentObject.firstName " " studentObject.lastName;}};} /script The studentController is defined as a JavaScript object with scope as anargument. The scope refers to application which uses the studentController object. The scope.student is a property of studentController object. The firstName and the lastName are two properties of scope.student object.We pass the default values to them. The property fullName is the function of scope.student object, which returnsthe combined name.19

Angular JS In the fullName function, we get the student object and then return thecombi

AngularJS i About the Tutorial AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free