SlideShare une entreprise Scribd logo
1  sur  25
Introduction to SPA
Angular JS
Mustafa M. Gamal
mustafa@moveitgate.com
AngularJs: First Glance
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
</head>
<body>
<p>Nothing here {{'yet' + '!'}}</p>
</body>
</html>
Tell Angular if the entire html page or only a portion
of it should be treated as the Angular application.
• Templating – a binding,
denoted by double-curlies {{
}}
• binding will result in
efficient continuous updates
whenever the result of the
expression evaluation
changes.
<script>
angular.element(document).ready(function() {
angular.bootstrap(document);});
</script>
App Bootstrap
• The injector that will be used for dependency
injection within this app is created.
• The injector will then create the root scope
that will become the context for the model of
our application.
• Angular will then "compile" the DOM starting
at the ngApp root element, processing any
directives and bindings found along the way.
MVC
<html lang="en" ng-app>
<head>
....
<script
src="lib/angular/angular.js"></script>
<script
src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">
<ul>
<li ng-repeat="phone in phones">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</body>
</html>
app/js/controllers.js
function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster
with Nexus S."},
{"name": "Motorola XOOM™ with Wi-
Fi",
"snippet": "The Next, Next
Generation tablet."},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next
Generation tablet."}
];
}
MVC
ViewModel
Controller
Actions
$scope.model
$scope.model
MVC
Filters
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->
Search: <input ng-model="query">
</div>
<div class="span10">
<!--Body content-->
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
Filters
Order By
HTML
...
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>
Controller
function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster
with Nexus S.",
"age": 0},
{"name": "Motorola XOOM™ with Wi-
Fi",
"snippet": "The Next, Next
Generation tablet.",
"age": 1},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next
Generation tablet.",
"age": 2}
];
$scope.orderProp = 'age';
}
AJAX Request
• $http service used to make
an HTTP request to web
server to fetch data
app/phones/phones.json
• Understand Json format
• returns a promise object
with a success method
function PhoneListCtrl($scope,
$http) {
$http
.get('phones/phones.json').
success(function(data) {
$scope.phones = data;
})
.error(function(){
alert("Error loading
data");
});
$scope.orderProp = 'age';
}
Promise pattern
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function () {
scope.$apply(function () {
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
});
}, 1000);
return deferred.promise;
}
var promise = asyncGreet('Robin Hood');
promise.then(function (greeting) {
alert('Success: ' + greeting);
}, function (reason) {
alert('Failed: ' + reason);
});
$http function
$http({ method: 'GET', url: '/someUrl' }).
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.
});
$http configurations
• method – {string} – HTTP method (e.g. 'GET', 'POST', etc)
• url – {string} – Absolute or relative URL of the resource that is being
requested.
• Params: Map of strings or objects => turned to ?
key1=value1&key2=value2 after the url. If the value is not a string, it will
be JSONified.
• data – {string|Object} – Data to be sent as the request message data.
• headers – {Object} – Map of strings representing HTTP headers to send to
the server.
• cache – {boolean|Cache} – If true, a default $http cache will be used to
cache the GET request, otherwise if a cache instance built with $
cacheFactory, this cache will be used for caching.
• timeout – {number} – timeout in milliseconds.
Dependency Injection - 1
function PhoneListCtrl($scope, $http) {
$http.get('phones/phones.jsoqn').success(function(data) {
$scope.phones = data;
})
.error(function(){
alert("Error loading data");
});
$scope.orderProp = 'age';
}
PhoneListCtrl.$inject = ['$scope', '$http'];
Dependency Injection - 2
var PhoneListCtrl = ['$scope', '$http',
function ($scope, $http)
{
$http.get('phones/phones.json').success(function
(data) {
$scope.phones = data;
})
.error(function(){
alert("Error loading data");
});
$scope.orderProp = 'age';
}];
Template
<ul class="phones">
<li ng-repeat="phone in phones | filter:query |
orderBy:orderProp" class="thumbnail">
<a href="#/phones/{{phone.id}}" class="thumb"><img
ng-src="{{phone.imageUrl}}"></a>
<a href="#/phones/{{phone.id}}">{{phone.name}}</a>
<p>{{phone.snippet}}</p>
</li>
</ul>
Multiple Views, Routing and Layout
Template
• A common template for all views in application
• Partial template included based on current rout
• $routeProvider provides $route service. which
wires together controllers, view templates, and
the current URL location in the browser.
• This will lets us utilize the browser's history
Defining module
angular.module('phonecat', []).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/phones',
{ templateUrl: 'partials/phone-list.html',
controller: PhoneListCtrl })
.when('/phones/:phoneId',
{ templateUrl: 'partials/phone-detail.html',
controller: PhoneDetailCtrl })
.otherwise({ redirectTo: '/phones' });
}]);
Rout Injected configuration
<html ng-app="phonecat">
Controller and Routing
function PhoneDetailCtrl($scope,
$routeParams) {
$scope.phoneId =
$routeParams.phoneId;
}
//url: http://localhost:8080/phones/5
Pattern in previous slide
.when('/phones/:phoneId',
{ templateUrl: 'partials/phone-detail.html',
controller: PhoneDetailCtrl })
Views and Tmplates
Intex.html
<html lang="en" ng-app="phonecat">
<head>
...
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
 
<div ng-view></div>
 
</body>
</html>
Templates
• app/partials/phone-
list.html
• app/partials/phone-
detail.html
Details view
<img ng-src="{{phone.images[0]}}"
class="phone">
<h1>{{phone.name}}</h1>
<p>{{phone.description}}</p>
<ul class="phone-thumbs">
<li ng-repeat="img in
phone.images">
<img ng-src="{{img}}">
</li>
</ul>
...
controller
function
PhoneDetailCtrl($scope,
$routeParams, $http) {
$http.get('phones/' +
$routeParams.phoneId +
'.json').success(function
(data) {
$scope.phone =
data;
});
}
Module Template Filters
Without filters With filter
app/js/app.js
angular.module
('phonecat',
['phonecatFilters']).
app/js/filters.js
angular.module
('phonecatFilters',
[]).filter('checkmark',
function() {
return
function(input) {
return input ?
'u2713' : 'u2718';
};
});
Template - Filters
<span>Connectivity</span>
<dl>
<dt>Network Support</dt>
<dd>{{phone.connectivity.cell}}</dd>
<dt>WiFi</dt>
<dd>{{phone.connectivity.wifi}}</dd>
<dt>Bluetooth</dt>
<dd>{{phone.connectivity.bluetooth}}</dd>
<dt>Infrared</dt>
<dd>
{{phone.connectivity.infrared | checkmark}}
</dd>
<dt>GPS</dt>
<dd>
{{phone.connectivity.gps | checkmark}}
</dd>
</dl>
• Filtere:
• {{ expression | filter }}
Views events and Controller actions
function
PhoneDetailCtrl($scope,
$routeParams, $http) {
...
$scope.setImage =
function(imageUrl) {
$scope.mainImageUrl =
imageUrl;
}
}
<img ng-
src="{{mainImageUrl}}"
class="phone">
...
<ul class="phone-thumbs">
<li ng-repeat="img in
phone.images">
<img ng-src="{{img}}"
ng-click="setImage(img)">
</li>
</ul>

Contenu connexe

Tendances

Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
JavaScript Testing for Rubyists
JavaScript Testing for RubyistsJavaScript Testing for Rubyists
JavaScript Testing for Rubyists
Jamie Dyer
 

Tendances (20)

Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Working with AFNetworking
Working with AFNetworkingWorking with AFNetworking
Working with AFNetworking
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Tools for Solving Performance Issues
Tools for Solving Performance IssuesTools for Solving Performance Issues
Tools for Solving Performance Issues
 
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIs
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjC
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
 
Angular mix chrisnoring
Angular mix chrisnoringAngular mix chrisnoring
Angular mix chrisnoring
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
ngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency InjectionngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency Injection
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
JavaScript Testing for Rubyists
JavaScript Testing for RubyistsJavaScript Testing for Rubyists
JavaScript Testing for Rubyists
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 

En vedette

Soa Runtime Governance Practices
Soa Runtime Governance PracticesSoa Runtime Governance Practices
Soa Runtime Governance Practices
Michiel.Kemperman
 

En vedette (7)

Angular JS Introduction
Angular JS IntroductionAngular JS Introduction
Angular JS Introduction
 
Angular js
Angular jsAngular js
Angular js
 
Soa Runtime Governance Practices
Soa Runtime Governance PracticesSoa Runtime Governance Practices
Soa Runtime Governance Practices
 
Angular Seminar-js
Angular Seminar-jsAngular Seminar-js
Angular Seminar-js
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
Introduction to Angular JS
Introduction to Angular JSIntroduction to Angular JS
Introduction to Angular JS
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 

Similaire à Introduction to Angular js

Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 

Similaire à Introduction to Angular js (20)

Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
REST API for your WP7 App
REST API for your WP7 AppREST API for your WP7 App
REST API for your WP7 App
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Frontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and HowFrontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and How
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Introduction to Angular js

  • 1. Introduction to SPA Angular JS Mustafa M. Gamal mustafa@moveitgate.com
  • 2. AngularJs: First Glance <!doctype html> <html lang="en" ng-app> <head> <meta charset="utf-8"> <title>My HTML File</title> <link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="css/bootstrap.css"> <script src="lib/angular/angular.js"></script> </head> <body> <p>Nothing here {{'yet' + '!'}}</p> </body> </html> Tell Angular if the entire html page or only a portion of it should be treated as the Angular application. • Templating – a binding, denoted by double-curlies {{ }} • binding will result in efficient continuous updates whenever the result of the expression evaluation changes. <script> angular.element(document).ready(function() { angular.bootstrap(document);}); </script>
  • 3. App Bootstrap • The injector that will be used for dependency injection within this app is created. • The injector will then create the root scope that will become the context for the model of our application. • Angular will then "compile" the DOM starting at the ngApp root element, processing any directives and bindings found along the way.
  • 4. MVC <html lang="en" ng-app> <head> .... <script src="lib/angular/angular.js"></script> <script src="js/controllers.js"></script> </head> <body ng-controller="PhoneListCtrl"> <ul> <li ng-repeat="phone in phones"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> </body> </html> app/js/controllers.js function PhoneListCtrl($scope) { $scope.phones = [ {"name": "Nexus S", "snippet": "Fast just got faster with Nexus S."}, {"name": "Motorola XOOM™ with Wi- Fi", "snippet": "The Next, Next Generation tablet."}, {"name": "MOTOROLA XOOM™", "snippet": "The Next, Next Generation tablet."} ]; }
  • 6. MVC
  • 7. Filters <div class="container-fluid"> <div class="row-fluid"> <div class="span2"> <!--Sidebar content--> Search: <input ng-model="query"> </div> <div class="span10"> <!--Body content--> <ul class="phones"> <li ng-repeat="phone in phones | filter:query"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> </div> </div>
  • 9. Order By HTML ... 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> Controller function PhoneListCtrl($scope) { $scope.phones = [ {"name": "Nexus S", "snippet": "Fast just got faster with Nexus S.", "age": 0}, {"name": "Motorola XOOM™ with Wi- Fi", "snippet": "The Next, Next Generation tablet.", "age": 1}, {"name": "MOTOROLA XOOM™", "snippet": "The Next, Next Generation tablet.", "age": 2} ]; $scope.orderProp = 'age'; }
  • 10. AJAX Request • $http service used to make an HTTP request to web server to fetch data app/phones/phones.json • Understand Json format • returns a promise object with a success method function PhoneListCtrl($scope, $http) { $http .get('phones/phones.json'). success(function(data) { $scope.phones = data; }) .error(function(){ alert("Error loading data"); }); $scope.orderProp = 'age'; }
  • 11. Promise pattern function asyncGreet(name) { var deferred = $q.defer(); setTimeout(function () { scope.$apply(function () { if (okToGreet(name)) { deferred.resolve('Hello, ' + name + '!'); } else { deferred.reject('Greeting ' + name + ' is not allowed.'); } }); }, 1000); return deferred.promise; } var promise = asyncGreet('Robin Hood'); promise.then(function (greeting) { alert('Success: ' + greeting); }, function (reason) { alert('Failed: ' + reason); });
  • 12. $http function $http({ method: 'GET', url: '/someUrl' }). 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. });
  • 13. $http configurations • method – {string} – HTTP method (e.g. 'GET', 'POST', etc) • url – {string} – Absolute or relative URL of the resource that is being requested. • Params: Map of strings or objects => turned to ? key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. • data – {string|Object} – Data to be sent as the request message data. • headers – {Object} – Map of strings representing HTTP headers to send to the server. • cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $ cacheFactory, this cache will be used for caching. • timeout – {number} – timeout in milliseconds.
  • 14. Dependency Injection - 1 function PhoneListCtrl($scope, $http) { $http.get('phones/phones.jsoqn').success(function(data) { $scope.phones = data; }) .error(function(){ alert("Error loading data"); }); $scope.orderProp = 'age'; } PhoneListCtrl.$inject = ['$scope', '$http'];
  • 15. Dependency Injection - 2 var PhoneListCtrl = ['$scope', '$http', function ($scope, $http) { $http.get('phones/phones.json').success(function (data) { $scope.phones = data; }) .error(function(){ alert("Error loading data"); }); $scope.orderProp = 'age'; }];
  • 16. Template <ul class="phones"> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp" class="thumbnail"> <a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a> <a href="#/phones/{{phone.id}}">{{phone.name}}</a> <p>{{phone.snippet}}</p> </li> </ul>
  • 17. Multiple Views, Routing and Layout Template • A common template for all views in application • Partial template included based on current rout • $routeProvider provides $route service. which wires together controllers, view templates, and the current URL location in the browser. • This will lets us utilize the browser's history
  • 18. Defining module angular.module('phonecat', []). config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/phones', { templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl }) .when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl }) .otherwise({ redirectTo: '/phones' }); }]); Rout Injected configuration <html ng-app="phonecat">
  • 19. Controller and Routing function PhoneDetailCtrl($scope, $routeParams) { $scope.phoneId = $routeParams.phoneId; } //url: http://localhost:8080/phones/5 Pattern in previous slide .when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl })
  • 20. Views and Tmplates Intex.html <html lang="en" ng-app="phonecat"> <head> ... <script src="lib/angular/angular.js"></script> <script src="js/app.js"></script> <script src="js/controllers.js"></script> </head> <body>   <div ng-view></div>   </body> </html> Templates • app/partials/phone- list.html • app/partials/phone- detail.html
  • 21. Details view <img ng-src="{{phone.images[0]}}" class="phone"> <h1>{{phone.name}}</h1> <p>{{phone.description}}</p> <ul class="phone-thumbs"> <li ng-repeat="img in phone.images"> <img ng-src="{{img}}"> </li> </ul> ... controller function PhoneDetailCtrl($scope, $routeParams, $http) { $http.get('phones/' + $routeParams.phoneId + '.json').success(function (data) { $scope.phone = data; }); }
  • 22. Module Template Filters Without filters With filter
  • 24. Template - Filters <span>Connectivity</span> <dl> <dt>Network Support</dt> <dd>{{phone.connectivity.cell}}</dd> <dt>WiFi</dt> <dd>{{phone.connectivity.wifi}}</dd> <dt>Bluetooth</dt> <dd>{{phone.connectivity.bluetooth}}</dd> <dt>Infrared</dt> <dd> {{phone.connectivity.infrared | checkmark}} </dd> <dt>GPS</dt> <dd> {{phone.connectivity.gps | checkmark}} </dd> </dl> • Filtere: • {{ expression | filter }}
  • 25. Views events and Controller actions function PhoneDetailCtrl($scope, $routeParams, $http) { ... $scope.setImage = function(imageUrl) { $scope.mainImageUrl = imageUrl; } } <img ng- src="{{mainImageUrl}}" class="phone"> ... <ul class="phone-thumbs"> <li ng-repeat="img in phone.images"> <img ng-src="{{img}}" ng-click="setImage(img)"> </li> </ul>