SlideShare une entreprise Scribd logo
1  sur  50
Getting Started
with
Akshay Mathur
What is Angular
• Browser-side MVC toolkit
– For creating Single Page Web Apps
– With less custom code
• All in one JavaScript framework
– Encapsulates many concepts within
– jQuery may not be required
• Resembles more with server side Frameworks
Prerequisites
• Advance JS objects and objects instances
• Model, View, Controller and App objects
• Data Bindings (one-way and two way)
• Client-side templates
• URL routing
• Module definition
• Module dependency
• Asynchronous programing
Custom HTML Attributes
• To any HTML node, any arbitrary attribute can
be added
<div howdy=“I am fine”></div>
• Browsers simply ignore such attributes
• These attributes can be read by JavaScript
Directives
• Angular uses custom HTML attributes for its
use
– They call it directives
• Angular script reads these directives and acts
accordingly
• HTML tags are also used as directives
– Standard HTML tags with changed behavior
– Custom HTML tags
ng-app
• The ng-app directive serves two purposes
– Tells Angular about the root node for the application
– Assigns witch app object (module) to use
<html ng-app="phonecatApp">
<head>
<script src=”angular.js"></script>
</head>
<body> … …</body>
</html>
Creating Angular Module
• All modules (angular core or 3rd party) that
should be available to an application must be
registered
• The angular.module is a global place for
creating, registering and retrieving Angular
modules
angular.module(name,
[requires],
configFn);
App Object
• App may be used as the top level Angular Module
– All other objects are defined as member of this object
var phonecatApp =
angular.module(
'phonecatApp',
[]
);
The Phone Catalogue App
• Nexus S
Fast just got faster with
Nexus S.
• Motorola XOOM with Wi-Fi
The Next, Next Generation
tablet.
<ul>
<li>
<span>Nexus S</span>
<p> Fast just got
faster with Nexus S. </p>
</li>
<li>
<span>Motorola XOOM
with Wi-Fi</span>
<p> The Next, Next
Generation tablet. </p>
</li>
</ul>
HTML Templates
• When similar HTML needs to be written for
different content, templates are used
• Template system allows to fill up data into
templates
– This is done via data binding expressions
• The template system also allows for basic
program constructs e.g. loops
JavaScript Template System
• Dynamically creates HTML code in JS
– Data driven HTML
– Allows variable substitution, looping and
conditional statements
• Generated HTML is inserted into the DOM for
changing part of the page on-the-fly
• Many libraries are available e.g. Handlebars,
DustJS, Mustache, UnderscoreJS etc.
– Angular has its own template system
@akshaymathu 11
View
• Object that holds visual representation of the
data
• Provides methods for
– Rendering the user interface
– Handling the user interaction within the view
• Angular uses template as view
• The view gets its data from its Model
– Each view has its own model
@akshaymathu 12
Model
• Object that holds data in a structural form
• Makes data available to view
• Acts as a unit of data
• By default Angular uses $scope object as
model
– Each view has its own model so the scope of
$scope is limited to the view
@akshaymathu 13
Value Substitution
• Values are passed to template using $scope
object
– Members of $scope can be used directly in template
• Items in {{ }} are treated as variables and replaced
by its values
<li>
<span>{{phone_name}}</span>
<p>{{phone_desc}}</p>
</li>
@akshaymathu 14
Looping
• Looping is done using ng-repeat directive
• Data passed to ng-repeat should be an Array
<li ng-repeat="phone in phones">
<span>{{phone.name}}</span>
<p>{{phone.desc}}</p>
</li>
@akshaymathu 15
Controller
• Object that acts as a glue to connects view
and model
• The ng-controller directive attaches controller
to the view
<ul ng-controller=
"PhoneListCtrl">
<li> … …</li>
</ul>
@akshaymathu 16
Passing Data to View
• Controller method of the App Object creates a
controller
• Value of $scope is set in the controller
phonecatApp.controller('PhoneListCtrl',
function ($scope) {
$scope.phones = [
{'name': 'Nexus S',
’desc': 'Fast just got faster'},
{'name': 'Motorola XOOM', ’desc': ’Next
Generation tablet.’}
];
}
);
Everything Together: HTML
<html ng-app="phonecatApp">
<head>
<script src=”angular.js"></script>
</head>
<body>
<ul ng-controller="PhoneListCtrl">
<li ng-repeat="phone in phones">
<span>{{phone.name}}</span>
<p>{{phone.desc}}</p>
</li>
</ul>
</body>
</html>
@akshaymathu 18
Everything Together: JS
var phonecatApp =
angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl',
function ($scope) {
$scope.phones = [
{'name': 'Nexus S',
’desc': 'Fast just got faster'},
{'name': 'Motorola XOOM',
’desc': ’Next Generation tablet.’}
];
}
);
Reading from Form Elements
• A model can be attached to form elements
– AngularJS updates the attached Model as value in
form element changes
<input ng-model="query">
– AngularJS also updates the value of form element
changes when the attached model is changed
Data Bindings
• Corresponding changes trigger as soon as data
changes at one place
• One way data binding
– Template re-renders as data in $scope changes
• Two way data binding
– Value of form element and attached model always
remain in sync
Modifying Data
• AngularJS provides a few readymade filter
functions for achieving certain effect
– Can be included within expressions in the
template
var val = 54.2
{{ val | number : 3}} // 54.200
• Option to write custom filters is available
Formatting Filters
• Number: Formats number
{{ val | number : 3}}
• Currency: Puts a currency identifier
{{amount | currency: "USD"}}
• Date: Formats date
{{today | date: 'medium'}}
• Lowercase/Uppercase
{{’somestr’| uppercase}}
• JSON: Formats JS object as string
{{ {'name':'value'} | json }}
Filtering Arrays
• Limit: Picks limited number of items
{{[1,2,3,4,5,6,7]| limitTo: 3 }}
• Filter: Picks items based on condition
{{[‘Bob’, ‘Mike’] | filter:
‘m’}}
• Order: Orders the array of objects in a field
{{[o1, o2] | orderBy: o1.f1}}
Filtering Repeater
<body>
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
<ul class="phones">
<li ng-repeat="phone in phones | filter: query |
orderBy: orderProp">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</body>
Creating Filter
• Custom filter cam be created using filter
method of Angular module
angular.module(
'phonecatFilters', []
).filter(’status',
filter_func);
Function Facts
• A function can be assigned to a variable
• A function can be defined within another function
• A function can return a function
function sqr(){
sq = function (x){
return x * x * x;
};
return sq;
}
My_sqr = sqr(); // function
My_sqr(3); // 27
@akshaymathu 27
Custom Filter
• Filter returns a function
– This function takes the value to be transformed as input
– Optionally other arguments can be taken
– Returns the transformed value as output
filter_func = function(){
return function(input){
return input ? ‘smart’: ‘dumb’
}
}
Complete Filter
Definition:
angular.module(
'phonecatFilters',
[]).filter(’status’, filter_func);
filter_func = function(){
return function(input){
return input ? ‘smart’: ‘dumb’;
}
});
Usage:
{{ phone_type | status }}
Question
• The filter is defined as a member of top level Angular
module named phonecatFilters
angular.module(
'phonecatFilters',
[]).filter(’status’, filter_func);
• How will this be available to the HTML template connected
to phonecatApp?
<html ng-app="phonecatApp">
var phonecatApp =
angular.module('phonecatApp’, []);
Dependency Injection
Object as Argument
• Objects can be passed to a function as an argument
• They proxy for named arguments
Say_hello = function (options){
if (typeof options === ‘Object’){
options.msg = (options.msg)?
options.msg : ’Hello!’;
}
alert(options.msg + ‘ ‘ + options.name);
}
Say_hello({name: ‘Akshay’});
@akshaymathu 32
Using Functions as Objects
• Functions are actually First Class objects
So we can change
User= {}
User.name = ‘Akshay’
User.greet = function(){
alert(‘Hello ’ + User.name)
}
to
User = function(){
this.name = ‘Akshay’
this.greet = function(){
alert(‘Hello ’ + this.name)
}
}
@akshaymathu 33
Creating Instances
• Now the object instance can be created using
new keyword
user1 = new User; user1.name
//Akshay user1.greet() //Hello
Akshay
@akshaymathu 34
Class Constructor
• The main object function can take arguments for
initializing properties
User = function(name){
this.name = name;
this.greet = function(){
alert(‘Hello ’ + this.name)
}
}
user1 = new User(‘Cerri’);
user1.greet() //Hello Cerri
@akshaymathu 35
Extending a Class
• More functions and properties can be defined
extending the prototype of the class
User.prototype.setGender =
function(gender){
this.gender = gender;
};
User.prototype.sayGender =
function(){
alert(this.name + ‘ is ’ +
this.gender);
};
@akshaymathu 36
What is Dependency Injection
• A software design pattern that deals with how
code gets hold of its dependencies
• The best option is that the dependency is
passed in to the function or the object where
it is needed
Passing Dependency
• If the dependency is simply handed to the component, it
removes the responsibility of locating the dependency
function SomeClass(greeter) {
this.greeter = greeter;
}
SomeClass.prototype.doSomething =
function(name) {
this.greeter.greet(name);
}
Injector
• To manage the responsibility of dependency
creation, each Angular application has an injector.
• The injector is a ‘service locator’ that is
responsible for construction and lookup of
dependencies.
• How does the injector know what service needs
to be injected?
How injector knows..
• Infer the name of dependencies from the
name of function arguments
function MyCtlr($scope,
greeter){}
• Pass to injector
MyCtlr.$inject = [‘$scope’,
‘greeter’]
Making the Filter Available
• While creating a module, other required
modules can be passed as dependency list
var phonecatApp =
angular.module('phonecatApp’,
[‘phonecatFilters’]);
{{ phone_type | status }}
Services
Angular Services
• What is a service?
– A system doing work for us
• Angular services are substitutable objects
– Wired together using dependency injection
• Angular services are:
– Lazily instantiated
– Singletons
Registering Custom Service
var myMod = angular.module('myMod', []);
myMod.factory('serviceId’, function() {
var shinyNewServiceInstance;
//factory function body that constructs
shinyNewServiceInstance
return shinyNewServiceInstance;
});
Built-in Services
• Angular provides built-in services for various
needs
– $filter: for formatting the data
– $window: for accessing window object
– $location: for parsing URL
– $timeout: a wrapper on setTimeout
– $http: for communicating with server using XHR or
JSONP
– …
Talking to Server
• A way in web browser to communicate with
server without reloading the page
• XmlHttpRequest (XHR) object can also create
HTTP request and receive response
– The request happens asynchronously
• Other operations on page are allowed during the
request
– Received data does not render automatically
• Data needs to be received in a callback function and
used programmatically
@akshaymathu 47
Asynchronous JavaScript & XML
AJAX Call in jQuery
$.ajax({
url: ‘/my_ajax_target’,
type: ‘POST’,
data: {id: 2},
success: function(response){
alert(‘Hello! ‘ + response.name);
},
error: function(){
alert(‘Please try later’);
}
});
@akshaymathu 48
AJAX Call in Angular
$http({
method: 'GET',
url: '/someUrl’,
params: {id: 2}
}
).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}
).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
}
);
Shortcut Methods
• For HTTP methods:
– GET: $http.get('/someUrl’)
– POST: $http.post('/someUrl', data)
– PUT: $http.put
– DELETE: $http.delete
• For getting only headers
– $http.head
• For cross-domain JSON (JSONP) call
– $http.jsonp(’http://domain/Url’)

Contenu connexe

Tendances

Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseEPAM Systems
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedStéphane Bégaudeau
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014Sarah Hudson
 
Angularjs architecture
Angularjs architectureAngularjs architecture
Angularjs architectureMichael He
 
Step by Step - AngularJS
Step by Step - AngularJSStep by Step - AngularJS
Step by Step - AngularJSInfragistics
 
Angular JS tutorial
Angular JS tutorialAngular JS tutorial
Angular JS tutorialcncwebworld
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBApaichon Punopas
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS introdizabl
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular jsTamer Solieman
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
AngularJs (1.x) Presentation
AngularJs (1.x) PresentationAngularJs (1.x) Presentation
AngularJs (1.x) PresentationRaghubir Singh
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at DatacomDavid Xi Peng Yang
 

Tendances (20)

Angular js
Angular jsAngular js
Angular js
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
 
Angularjs architecture
Angularjs architectureAngularjs architecture
Angularjs architecture
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Step by Step - AngularJS
Step by Step - AngularJSStep by Step - AngularJS
Step by Step - AngularJS
 
Angular JS tutorial
Angular JS tutorialAngular JS tutorial
Angular JS tutorial
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
AngularJs (1.x) Presentation
AngularJs (1.x) PresentationAngularJs (1.x) Presentation
AngularJs (1.x) Presentation
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at Datacom
 

En vedette

Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework Sakthi Bro
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Understanding Native, Hybrid, and Web Mobile Architectures
Understanding Native, Hybrid, and Web Mobile ArchitecturesUnderstanding Native, Hybrid, and Web Mobile Architectures
Understanding Native, Hybrid, and Web Mobile ArchitecturesSalesforce Developers
 
Angular js best practice
Angular js best practiceAngular js best practice
Angular js best practiceMatteo Scandolo
 
Git/Github & Salesforce
Git/Github & Salesforce Git/Github & Salesforce
Git/Github & Salesforce Gordon Bockus
 
AngularJS + React
AngularJS + ReactAngularJS + React
AngularJS + Reactjustvamp
 
Design patterns through refactoring
Design patterns through refactoringDesign patterns through refactoring
Design patterns through refactoringGanesh Samarthyam
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React TogetherSebastian Pederiva
 
Kế hoạch thi HK2 2015-2016
Kế hoạch thi HK2 2015-2016Kế hoạch thi HK2 2015-2016
Kế hoạch thi HK2 2015-2016Mãi Mãi Yêu
 
Pieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React NativePieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React Nativetlv-ios-dev
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
 
Multiorg Collaboration Using Salesforce S2S
Multiorg Collaboration Using Salesforce S2SMultiorg Collaboration Using Salesforce S2S
Multiorg Collaboration Using Salesforce S2SMayur Shintre
 

En vedette (20)

Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Get satrted angular js
Get satrted angular jsGet satrted angular js
Get satrted angular js
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Write bulletproof trigger code
Write bulletproof trigger codeWrite bulletproof trigger code
Write bulletproof trigger code
 
Understanding Native, Hybrid, and Web Mobile Architectures
Understanding Native, Hybrid, and Web Mobile ArchitecturesUnderstanding Native, Hybrid, and Web Mobile Architectures
Understanding Native, Hybrid, and Web Mobile Architectures
 
Angular js best practice
Angular js best practiceAngular js best practice
Angular js best practice
 
Angular js
Angular jsAngular js
Angular js
 
Git/Github & Salesforce
Git/Github & Salesforce Git/Github & Salesforce
Git/Github & Salesforce
 
AngularJS + React
AngularJS + ReactAngularJS + React
AngularJS + React
 
Design patterns through refactoring
Design patterns through refactoringDesign patterns through refactoring
Design patterns through refactoring
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React Together
 
Kế hoạch thi HK2 2015-2016
Kế hoạch thi HK2 2015-2016Kế hoạch thi HK2 2015-2016
Kế hoạch thi HK2 2015-2016
 
Design Patterns in .Net
Design Patterns in .NetDesign Patterns in .Net
Design Patterns in .Net
 
Pieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React NativePieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React Native
 
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
Node js meetup
Node js meetupNode js meetup
Node js meetup
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Multiorg Collaboration Using Salesforce S2S
Multiorg Collaboration Using Salesforce S2SMultiorg Collaboration Using Salesforce S2S
Multiorg Collaboration Using Salesforce S2S
 
C#.net
C#.netC#.net
C#.net
 

Similaire à Getting Started with Angular JS

angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs WorkshopRan Wahle
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
 
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...Sencha
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english versionSabino Labarile
 
BackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsBackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsJoseph Khan
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Angular Presentation
Angular PresentationAngular Presentation
Angular PresentationAdam Moore
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSAkshay Mathur
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Roy de Kleijn
 
Single page apps_with_cf_and_angular[1]
Single page apps_with_cf_and_angular[1]Single page apps_with_cf_and_angular[1]
Single page apps_with_cf_and_angular[1]ColdFusionConference
 
Introduction to Polymer
Introduction to PolymerIntroduction to Polymer
Introduction to PolymerEgor Miasnikov
 
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Neelkanth Sachdeva
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Knoldus Inc.
 

Similaire à Getting Started with Angular JS (20)

angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
 
BackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsBackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applications
 
Angularjs
AngularjsAngularjs
Angularjs
 
AngularJS
AngularJSAngularJS
AngularJS
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
AngularJS
AngularJSAngularJS
AngularJS
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
 
Single page apps_with_cf_and_angular[1]
Single page apps_with_cf_and_angular[1]Single page apps_with_cf_and_angular[1]
Single page apps_with_cf_and_angular[1]
 
Introduction to Polymer
Introduction to PolymerIntroduction to Polymer
Introduction to Polymer
 
Angular js for Beginnners
Angular js for BeginnnersAngular js for Beginnners
Angular js for Beginnners
 
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 

Plus de Akshay Mathur

Documentation with Sphinx
Documentation with SphinxDocumentation with Sphinx
Documentation with SphinxAkshay Mathur
 
Kubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTechKubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTechAkshay Mathur
 
Security and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in KubernetesSecurity and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in KubernetesAkshay Mathur
 
Enhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices ApplicationsEnhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices ApplicationsAkshay Mathur
 
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...Akshay Mathur
 
Kubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning ControllerKubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning ControllerAkshay Mathur
 
Cloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADSCloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADSAkshay Mathur
 
Shared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWSShared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWSAkshay Mathur
 
Techniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloudTechniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloudAkshay Mathur
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptAkshay Mathur
 
Releasing Software Without Testing Team
Releasing Software Without Testing TeamReleasing Software Without Testing Team
Releasing Software Without Testing TeamAkshay Mathur
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQueryAkshay Mathur
 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with WebAkshay Mathur
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with JavascriptAkshay Mathur
 
Using Google App Engine Python
Using Google App Engine PythonUsing Google App Engine Python
Using Google App Engine PythonAkshay Mathur
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page WebappAkshay Mathur
 

Plus de Akshay Mathur (20)

Documentation with Sphinx
Documentation with SphinxDocumentation with Sphinx
Documentation with Sphinx
 
Kubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTechKubernetes Journey of a Large FinTech
Kubernetes Journey of a Large FinTech
 
Security and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in KubernetesSecurity and Observability of Application Traffic in Kubernetes
Security and Observability of Application Traffic in Kubernetes
 
Enhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices ApplicationsEnhanced Security and Visibility for Microservices Applications
Enhanced Security and Visibility for Microservices Applications
 
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...Considerations for East-West Traffic Security and Analytics for Kubernetes En...
Considerations for East-West Traffic Security and Analytics for Kubernetes En...
 
Kubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning ControllerKubernetes as Orchestrator for A10 Lightning Controller
Kubernetes as Orchestrator for A10 Lightning Controller
 
Cloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADSCloud Bursting with A10 Lightning ADS
Cloud Bursting with A10 Lightning ADS
 
Shared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWSShared Security Responsibility Model of AWS
Shared Security Responsibility Model of AWS
 
Techniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloudTechniques for scaling application with security and visibility in cloud
Techniques for scaling application with security and visibility in cloud
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Object Oriented Programing in JavaScript
Object Oriented Programing in JavaScriptObject Oriented Programing in JavaScript
Object Oriented Programing in JavaScript
 
Releasing Software Without Testing Team
Releasing Software Without Testing TeamReleasing Software Without Testing Team
Releasing Software Without Testing Team
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with Web
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with Javascript
 
Using Google App Engine Python
Using Google App Engine PythonUsing Google App Engine Python
Using Google App Engine Python
 
Working with GIT
Working with GITWorking with GIT
Working with GIT
 
Testing Single Page Webapp
Testing Single Page WebappTesting Single Page Webapp
Testing Single Page Webapp
 
Mongo db
Mongo dbMongo db
Mongo db
 

Dernier

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 

Dernier (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 

Getting Started with Angular JS

  • 2. What is Angular • Browser-side MVC toolkit – For creating Single Page Web Apps – With less custom code • All in one JavaScript framework – Encapsulates many concepts within – jQuery may not be required • Resembles more with server side Frameworks
  • 3. Prerequisites • Advance JS objects and objects instances • Model, View, Controller and App objects • Data Bindings (one-way and two way) • Client-side templates • URL routing • Module definition • Module dependency • Asynchronous programing
  • 4. Custom HTML Attributes • To any HTML node, any arbitrary attribute can be added <div howdy=“I am fine”></div> • Browsers simply ignore such attributes • These attributes can be read by JavaScript
  • 5. Directives • Angular uses custom HTML attributes for its use – They call it directives • Angular script reads these directives and acts accordingly • HTML tags are also used as directives – Standard HTML tags with changed behavior – Custom HTML tags
  • 6. ng-app • The ng-app directive serves two purposes – Tells Angular about the root node for the application – Assigns witch app object (module) to use <html ng-app="phonecatApp"> <head> <script src=”angular.js"></script> </head> <body> … …</body> </html>
  • 7. Creating Angular Module • All modules (angular core or 3rd party) that should be available to an application must be registered • The angular.module is a global place for creating, registering and retrieving Angular modules angular.module(name, [requires], configFn);
  • 8. App Object • App may be used as the top level Angular Module – All other objects are defined as member of this object var phonecatApp = angular.module( 'phonecatApp', [] );
  • 9. The Phone Catalogue App • Nexus S Fast just got faster with Nexus S. • Motorola XOOM with Wi-Fi The Next, Next Generation tablet. <ul> <li> <span>Nexus S</span> <p> Fast just got faster with Nexus S. </p> </li> <li> <span>Motorola XOOM with Wi-Fi</span> <p> The Next, Next Generation tablet. </p> </li> </ul>
  • 10. HTML Templates • When similar HTML needs to be written for different content, templates are used • Template system allows to fill up data into templates – This is done via data binding expressions • The template system also allows for basic program constructs e.g. loops
  • 11. JavaScript Template System • Dynamically creates HTML code in JS – Data driven HTML – Allows variable substitution, looping and conditional statements • Generated HTML is inserted into the DOM for changing part of the page on-the-fly • Many libraries are available e.g. Handlebars, DustJS, Mustache, UnderscoreJS etc. – Angular has its own template system @akshaymathu 11
  • 12. View • Object that holds visual representation of the data • Provides methods for – Rendering the user interface – Handling the user interaction within the view • Angular uses template as view • The view gets its data from its Model – Each view has its own model @akshaymathu 12
  • 13. Model • Object that holds data in a structural form • Makes data available to view • Acts as a unit of data • By default Angular uses $scope object as model – Each view has its own model so the scope of $scope is limited to the view @akshaymathu 13
  • 14. Value Substitution • Values are passed to template using $scope object – Members of $scope can be used directly in template • Items in {{ }} are treated as variables and replaced by its values <li> <span>{{phone_name}}</span> <p>{{phone_desc}}</p> </li> @akshaymathu 14
  • 15. Looping • Looping is done using ng-repeat directive • Data passed to ng-repeat should be an Array <li ng-repeat="phone in phones"> <span>{{phone.name}}</span> <p>{{phone.desc}}</p> </li> @akshaymathu 15
  • 16. Controller • Object that acts as a glue to connects view and model • The ng-controller directive attaches controller to the view <ul ng-controller= "PhoneListCtrl"> <li> … …</li> </ul> @akshaymathu 16
  • 17. Passing Data to View • Controller method of the App Object creates a controller • Value of $scope is set in the controller phonecatApp.controller('PhoneListCtrl', function ($scope) { $scope.phones = [ {'name': 'Nexus S', ’desc': 'Fast just got faster'}, {'name': 'Motorola XOOM', ’desc': ’Next Generation tablet.’} ]; } );
  • 18. Everything Together: HTML <html ng-app="phonecatApp"> <head> <script src=”angular.js"></script> </head> <body> <ul ng-controller="PhoneListCtrl"> <li ng-repeat="phone in phones"> <span>{{phone.name}}</span> <p>{{phone.desc}}</p> </li> </ul> </body> </html> @akshaymathu 18
  • 19. Everything Together: JS var phonecatApp = angular.module('phonecatApp', []); phonecatApp.controller('PhoneListCtrl', function ($scope) { $scope.phones = [ {'name': 'Nexus S', ’desc': 'Fast just got faster'}, {'name': 'Motorola XOOM', ’desc': ’Next Generation tablet.’} ]; } );
  • 20. Reading from Form Elements • A model can be attached to form elements – AngularJS updates the attached Model as value in form element changes <input ng-model="query"> – AngularJS also updates the value of form element changes when the attached model is changed
  • 21. Data Bindings • Corresponding changes trigger as soon as data changes at one place • One way data binding – Template re-renders as data in $scope changes • Two way data binding – Value of form element and attached model always remain in sync
  • 22. Modifying Data • AngularJS provides a few readymade filter functions for achieving certain effect – Can be included within expressions in the template var val = 54.2 {{ val | number : 3}} // 54.200 • Option to write custom filters is available
  • 23. Formatting Filters • Number: Formats number {{ val | number : 3}} • Currency: Puts a currency identifier {{amount | currency: "USD"}} • Date: Formats date {{today | date: 'medium'}} • Lowercase/Uppercase {{’somestr’| uppercase}} • JSON: Formats JS object as string {{ {'name':'value'} | json }}
  • 24. Filtering Arrays • Limit: Picks limited number of items {{[1,2,3,4,5,6,7]| limitTo: 3 }} • Filter: Picks items based on condition {{[‘Bob’, ‘Mike’] | filter: ‘m’}} • Order: Orders the array of objects in a field {{[o1, o2] | orderBy: o1.f1}}
  • 25. Filtering Repeater <body> Search: <input ng-model="query"> Sort by: <select ng-model="orderProp"> <option value="name">Alphabetical</option> <option value="age">Newest</option> </select> <ul class="phones"> <li ng-repeat="phone in phones | filter: query | orderBy: orderProp"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> </body>
  • 26. Creating Filter • Custom filter cam be created using filter method of Angular module angular.module( 'phonecatFilters', [] ).filter(’status', filter_func);
  • 27. Function Facts • A function can be assigned to a variable • A function can be defined within another function • A function can return a function function sqr(){ sq = function (x){ return x * x * x; }; return sq; } My_sqr = sqr(); // function My_sqr(3); // 27 @akshaymathu 27
  • 28. Custom Filter • Filter returns a function – This function takes the value to be transformed as input – Optionally other arguments can be taken – Returns the transformed value as output filter_func = function(){ return function(input){ return input ? ‘smart’: ‘dumb’ } }
  • 29. Complete Filter Definition: angular.module( 'phonecatFilters', []).filter(’status’, filter_func); filter_func = function(){ return function(input){ return input ? ‘smart’: ‘dumb’; } }); Usage: {{ phone_type | status }}
  • 30. Question • The filter is defined as a member of top level Angular module named phonecatFilters angular.module( 'phonecatFilters', []).filter(’status’, filter_func); • How will this be available to the HTML template connected to phonecatApp? <html ng-app="phonecatApp"> var phonecatApp = angular.module('phonecatApp’, []);
  • 32. Object as Argument • Objects can be passed to a function as an argument • They proxy for named arguments Say_hello = function (options){ if (typeof options === ‘Object’){ options.msg = (options.msg)? options.msg : ’Hello!’; } alert(options.msg + ‘ ‘ + options.name); } Say_hello({name: ‘Akshay’}); @akshaymathu 32
  • 33. Using Functions as Objects • Functions are actually First Class objects So we can change User= {} User.name = ‘Akshay’ User.greet = function(){ alert(‘Hello ’ + User.name) } to User = function(){ this.name = ‘Akshay’ this.greet = function(){ alert(‘Hello ’ + this.name) } } @akshaymathu 33
  • 34. Creating Instances • Now the object instance can be created using new keyword user1 = new User; user1.name //Akshay user1.greet() //Hello Akshay @akshaymathu 34
  • 35. Class Constructor • The main object function can take arguments for initializing properties User = function(name){ this.name = name; this.greet = function(){ alert(‘Hello ’ + this.name) } } user1 = new User(‘Cerri’); user1.greet() //Hello Cerri @akshaymathu 35
  • 36. Extending a Class • More functions and properties can be defined extending the prototype of the class User.prototype.setGender = function(gender){ this.gender = gender; }; User.prototype.sayGender = function(){ alert(this.name + ‘ is ’ + this.gender); }; @akshaymathu 36
  • 37. What is Dependency Injection • A software design pattern that deals with how code gets hold of its dependencies • The best option is that the dependency is passed in to the function or the object where it is needed
  • 38. Passing Dependency • If the dependency is simply handed to the component, it removes the responsibility of locating the dependency function SomeClass(greeter) { this.greeter = greeter; } SomeClass.prototype.doSomething = function(name) { this.greeter.greet(name); }
  • 39. Injector • To manage the responsibility of dependency creation, each Angular application has an injector. • The injector is a ‘service locator’ that is responsible for construction and lookup of dependencies. • How does the injector know what service needs to be injected?
  • 40. How injector knows.. • Infer the name of dependencies from the name of function arguments function MyCtlr($scope, greeter){} • Pass to injector MyCtlr.$inject = [‘$scope’, ‘greeter’]
  • 41. Making the Filter Available • While creating a module, other required modules can be passed as dependency list var phonecatApp = angular.module('phonecatApp’, [‘phonecatFilters’]); {{ phone_type | status }}
  • 43. Angular Services • What is a service? – A system doing work for us • Angular services are substitutable objects – Wired together using dependency injection • Angular services are: – Lazily instantiated – Singletons
  • 44. Registering Custom Service var myMod = angular.module('myMod', []); myMod.factory('serviceId’, function() { var shinyNewServiceInstance; //factory function body that constructs shinyNewServiceInstance return shinyNewServiceInstance; });
  • 45. Built-in Services • Angular provides built-in services for various needs – $filter: for formatting the data – $window: for accessing window object – $location: for parsing URL – $timeout: a wrapper on setTimeout – $http: for communicating with server using XHR or JSONP – …
  • 47. • A way in web browser to communicate with server without reloading the page • XmlHttpRequest (XHR) object can also create HTTP request and receive response – The request happens asynchronously • Other operations on page are allowed during the request – Received data does not render automatically • Data needs to be received in a callback function and used programmatically @akshaymathu 47 Asynchronous JavaScript & XML
  • 48. AJAX Call in jQuery $.ajax({ url: ‘/my_ajax_target’, type: ‘POST’, data: {id: 2}, success: function(response){ alert(‘Hello! ‘ + response.name); }, error: function(){ alert(‘Please try later’); } }); @akshaymathu 48
  • 49. AJAX Call in Angular $http({ method: 'GET', url: '/someUrl’, params: {id: 2} } ).success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available } ).error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. } );
  • 50. Shortcut Methods • For HTTP methods: – GET: $http.get('/someUrl’) – POST: $http.post('/someUrl', data) – PUT: $http.put – DELETE: $http.delete • For getting only headers – $http.head • For cross-domain JSON (JSONP) call – $http.jsonp(’http://domain/Url’)