SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
Introduction to

HTML enhanced for web apps!
by Marco Vito Moscaritolo / @mavimo
<!-­-­ directive: ng-­mavimo -­-­>
{ { me.name } } -> Marco Vito Moscaritolo
{ { me.role } } -> Developer
{ { me.company.name | link } } -> Agavee
{ { me.twitter | link } } -> @mavimo
What's AngularJS
AngularJS is a toolset for building the framework most suited to
your application development.
Heads Up
Starting from directives...
...adding controllers...
...and filters...
...using routing...
...manage resources...
...and fun :)
Directives
Directives are a way to teach HTML new tricks. During DOM
compilation directives are matched against the HTML and
executed. This allows directives to register behavior, or
transform the DOM.
<span ng-repeat="exp"></span>
<span class="ng-repeat: exp;"></span>
<ng-repeat></ng-repeat>
<!-- directive: ng-repeat exp -->

The directives can be placed in element names, attributes,
class names, as well as comments.
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"
</head>
<body>
<div>
<input type="text" ng-model="sample" placeholder="Enter text">
<hr>
<h1>{ { sample } }!</h1>
</div>
</body>
</html>
Write here...
<!doctype html>
<html ng-app>
<head>
<script src="js/angular.min.js" ></script>
<script src="js/demo.js" ></script>
</head>
<body>
<ul ng-controller="getGdgList">
<li ng-repeat="gdg in gdgs">{ {gdg.name} } have { {gdg.members} } members
</ul>
</body>
</html>
GDG Milan have 92 members
GDG Barcelona have 228 members
GDG Silicon Valley have 171 members
GDG Stockholm have 119 members
GDG Herzeliya have 140 members
GDG Ahmedabad have 78 members
GDG Lagos have 115 members
GDG Bangalore have 109 members
GDG Lima have 175 members
GDG L-Ab have 77 members
and also
ng-show
ng-switch
ng-class
...
Controllers
<!doctype html>
<html ng-app>
<head>
<script src="js/angular.min.js" ></script>
<script src="js/demo.js" ></script>
</head>
<body>
<ul ng-controller="getTweets">
<li ng-repeat="tweet in tweets"></li>
</ul>
</body>
</html>
function getTweets($scope, $http) {
var search = 'gdg';
var url = 'http://search.twitter.com/search.json?q=' + search;
$http({ method: 'GET', url: url })
.success(function(data, status, headers, config) {
$scope.tweets = data.results;
})
.error(function(data, status, headers, config) {
console.log('Error: fetch tweets');
$scope.tweets = {};
});
return $scope;
}
Methods in controller
function getTweets($scope, $http) {
// ...
$scope.getMore = function () {
// ...
}
// ...
return $scope;
}]);
<ul ng-controller="getTweets">
<li ng-repeat="tweet in tweets"></li>
<li ng-click="getMore()">Get more</li>
</ul>
Controller in module
var gdgApp = angular.module('gdgApp', []);
gdgApp.controller('getTweets', ['$scope', '$http', function($scope, $http) {
var search = 'gdg';
var url = 'http://search.twitter.com/search.json?q=' + search;
$http({ method: 'GET', url: url }).
success(function(data, status, headers, config) {
$scope.tweets = data.results;
}).
error(function(data, status, headers, config) {
console.log('Error: fetch tweets');
$scope.tweets = {};
});
return $scope;
}]);
Dependency Injection
(also know as Inversion of Control)
Dependency Injection (DI) is a software design pattern that
deals with how code gets hold of its dependencies.
Services
Angular services are singletons that carry out specific tasks.
Eg. $http service that provides low level access to the
browser's XMLHttpRequest object.
gdgApp.controller('getTweets', ['$scope', '$http', function($scope, $http) {
// ...
return $scope;
}]);
angular.module('gdgModuleAlarm', []).
factory('alarm', function($window) {
return {
alarm: function(text) {
$window.alert(text);
}
};
}
);
Injectors
// New injector created from the previus declared module.
var injector = angular.injector(['gdgModuleAlarm', 'ng']);
// Request any dependency from the injector
var a = injector.get('alarm');
// We can also force injecting using
var alarmFactory = function (my$window) {};
alarmFactory.$inject = ['$window'];
Filters
Filters perform data transformation.
They follow the spirit of UNIX filters and use similar syntax |
(pipe).
<!doctype html>
<html ng-app>
<head>
<script src="js/angular.min.js" ></script>
<script src="js/demo.js" ></script>
</head>
<body>
<a href="" ng-click="predicate = 'members'; reverse=!reverse"<Sort</a>
<ul ng-controller="getGdgList">
<li ng-repeat="gdg in gdgs | orderBy:predicate:reverse "> have members
</ul>
</body>
</html>
Sort

GDG MILAN have 92 members
GDG BARCELONA have 228 members
GDG SILICON VALLEY have 171 members
GDG STOCKHOLM have 119 members
GDG HERZELIYA have 140 members
GDG AHMEDABAD have 78 members
GDG LAGOS have 115 members
GDG BANGALORE have 109 members
GDG LIMA have 175 members
GDG L-AB have 77 members
Creating custom filters
angular.module('agaveeApp', [])
.filter('orderByVersion', function() {
return function(modules, version) {
var parseVersionString = function (str) { /* .. */ };
var vMinMet = function(vmin, vcurrent) { /* .. */ };
var result = [];
for (var i = 0; i < modules.length; i++) {
if (vMinMet(modules[i].version_added, version)) {
result[result.length] = modules[i];
}
}
return result;
};
});
Model
The model is the data which is merged
with the template to produce the view.
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"
</head>
<body>
<div>
<input type="text" ng-model="sample" placeholder="Enter text">
<hr>
<h1>!</h1>
</div>
</body>
</html>
Configuration
angular.module('gdgApp', [])
.constant('gdg', {
'url' : 'http://localhost:3000',
'token': 'e9adf82fd1cb716548ef1d4621a5935dcf869817'
})
// Configure $http
.config(['$httpProvider', 'gdg',
function ($httpProvider, gdg) {
$httpProvider.defaults.headers.common['X-gdg-API-Key'] = gdg.token;
}
]);
Routing
angular.module('gdgApp', [])
// Configure services
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/projects', {
templateUrl: 'views/projects.html',
controller: 'ProjectsCtrl'
});
$routeProvider.when('/projects/:project', {
templateUrl: 'views/project.html',
controller: 'ProjectCtrl'
});
$routeProvider.otherwise({redirectTo: '/projects'});
}]);
Resource
angular.module('resources.project', ['ngResource'])
.factory('Project', ['$http', '$resource', 'gdg', function ($http, gdg) {
return $resource(gdg.url + '/project/:projectId', {projectId:'@id'}, {
query : { method : 'GET', isArray:true},
create : { method : 'POST' },
save
: { method : 'PUT' },
delete : { method : 'DELETE' }
});
}]);
// ...
var p = new Project();
p.name = 'GDG Milan';
p.$save();
angular.module('resources.project', ['ngResource'])
.factory('Project', ['$http', 'gdg', function ($http, gdg) {
var Project = function (data) {
angular.extend(this, data);
};
// a static method to retrieve Project by ID
Project.get = function (id) {
return $http.get(gdg.url + '/projects/' + id).then(function (response) {
return new Project(response.data);
});
};
// an instance method to create a new Project
Project.prototype.create = function () {
var project = this;
return $http.post(gdg.url + '/projects.json', project).then(function (response)
project.id = response.data.id;
Testing
Karma - a test runner that fits all our needs.
Jasmine - Jasmine is a behavior-driven development
framework for testing JavaScript code.
describe('Controller: getGdgList', function () {
// load the controller's module
beforeEach(module('gdgApp'));
var getGdgList, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller) {
scope = {};
getGdgList = $controller('getGdgList', {
$scope: scope
});
}));
it('GDG List must display defined number of items', function () {
expect(scope.gdgs.length).toBe(10);
});
Angular 1.2
...is coming!
More modular
Introduce ng-animate (and related)
Support to mobile (÷/-)
Demo
?
Questions time
THE END

Marco Vito Moscaritolo / @mavimo

Más contenido relacionado

La actualidad más candente

Private slideshow
Private slideshowPrivate slideshow
Private slideshow
sblackman
 

La actualidad más candente (20)

Odoo - CMS performances optimization
Odoo - CMS performances optimizationOdoo - CMS performances optimization
Odoo - CMS performances optimization
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 
Angular js
Angular jsAngular js
Angular js
 
Angular js
Angular jsAngular js
Angular js
 
Learning Svelte
Learning SvelteLearning Svelte
Learning Svelte
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
[AngularJS] From Angular to Mobile in 30 minutes
[AngularJS] From Angular to Mobile in 30 minutes[AngularJS] From Angular to Mobile in 30 minutes
[AngularJS] From Angular to Mobile in 30 minutes
 
javascript examples
javascript examplesjavascript examples
javascript examples
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJS
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
Aleksey Bogachuk - "Offline Second"
Aleksey Bogachuk - "Offline Second"Aleksey Bogachuk - "Offline Second"
Aleksey Bogachuk - "Offline Second"
 
The Magic of Advanced Debugging
The Magic of Advanced DebuggingThe Magic of Advanced Debugging
The Magic of Advanced Debugging
 
implemetning google analytics - 2011-09-24 Google Devfest Chiangmai
implemetning google analytics - 2011-09-24 Google Devfest Chiangmaiimplemetning google analytics - 2011-09-24 Google Devfest Chiangmai
implemetning google analytics - 2011-09-24 Google Devfest Chiangmai
 

Destacado

Destacado (9)

Managing Quality in the Front End World
Managing Quality in the Front End WorldManaging Quality in the Front End World
Managing Quality in the Front End World
 
Modulo drupal dati_geofisici_applicazioni_scientifiche
Modulo drupal dati_geofisici_applicazioni_scientificheModulo drupal dati_geofisici_applicazioni_scientifiche
Modulo drupal dati_geofisici_applicazioni_scientifiche
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Drupal7
Drupal7Drupal7
Drupal7
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
Front End Optimization, 'The Cloud' can help you!
Front End Optimization, 'The Cloud' can help you!Front End Optimization, 'The Cloud' can help you!
Front End Optimization, 'The Cloud' can help you!
 
Organizza il lavoro
Organizza il lavoroOrganizza il lavoro
Organizza il lavoro
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
HTML5, il lato client della forza...
HTML5, il lato client della forza... HTML5, il lato client della forza...
HTML5, il lato client della forza...
 

Similar a Introduction to AngularJS

Similar a Introduction to AngularJS (20)

AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
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
 
Angular JS deep dive
Angular JS deep diveAngular JS deep dive
Angular JS deep dive
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJS
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Built in filters
Built in filtersBuilt in filters
Built in filters
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.pptDevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routing
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 
Custom directive and scopes
Custom directive and scopesCustom directive and scopes
Custom directive and scopes
 
Valentine with AngularJS
Valentine with AngularJSValentine with AngularJS
Valentine with AngularJS
 
Pengenalan AngularJS
Pengenalan AngularJSPengenalan AngularJS
Pengenalan AngularJS
 
Sharing Data between controllers in different ways.
Sharing Data between controllers in different ways.Sharing Data between controllers in different ways.
Sharing Data between controllers in different ways.
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Introduction to AngularJS

  • 1. Introduction to HTML enhanced for web apps! by Marco Vito Moscaritolo / @mavimo
  • 2. <!-­-­ directive: ng-­mavimo -­-­> { { me.name } } -> Marco Vito Moscaritolo { { me.role } } -> Developer { { me.company.name | link } } -> Agavee { { me.twitter | link } } -> @mavimo
  • 3. What's AngularJS AngularJS is a toolset for building the framework most suited to your application development.
  • 4. Heads Up Starting from directives... ...adding controllers... ...and filters... ...using routing... ...manage resources... ...and fun :)
  • 5. Directives Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM. <span ng-repeat="exp"></span> <span class="ng-repeat: exp;"></span> <ng-repeat></ng-repeat> <!-- directive: ng-repeat exp --> The directives can be placed in element names, attributes, class names, as well as comments.
  • 6. <!doctype html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js" </head> <body> <div> <input type="text" ng-model="sample" placeholder="Enter text"> <hr> <h1>{ { sample } }!</h1> </div> </body> </html>
  • 8. <!doctype html> <html ng-app> <head> <script src="js/angular.min.js" ></script> <script src="js/demo.js" ></script> </head> <body> <ul ng-controller="getGdgList"> <li ng-repeat="gdg in gdgs">{ {gdg.name} } have { {gdg.members} } members </ul> </body> </html>
  • 9. GDG Milan have 92 members GDG Barcelona have 228 members GDG Silicon Valley have 171 members GDG Stockholm have 119 members GDG Herzeliya have 140 members GDG Ahmedabad have 78 members GDG Lagos have 115 members GDG Bangalore have 109 members GDG Lima have 175 members GDG L-Ab have 77 members
  • 11. Controllers <!doctype html> <html ng-app> <head> <script src="js/angular.min.js" ></script> <script src="js/demo.js" ></script> </head> <body> <ul ng-controller="getTweets"> <li ng-repeat="tweet in tweets"></li> </ul> </body> </html>
  • 12. function getTweets($scope, $http) { var search = 'gdg'; var url = 'http://search.twitter.com/search.json?q=' + search; $http({ method: 'GET', url: url }) .success(function(data, status, headers, config) { $scope.tweets = data.results; }) .error(function(data, status, headers, config) { console.log('Error: fetch tweets'); $scope.tweets = {}; }); return $scope; }
  • 13. Methods in controller function getTweets($scope, $http) { // ... $scope.getMore = function () { // ... } // ... return $scope; }]); <ul ng-controller="getTweets"> <li ng-repeat="tweet in tweets"></li> <li ng-click="getMore()">Get more</li> </ul>
  • 14. Controller in module var gdgApp = angular.module('gdgApp', []); gdgApp.controller('getTweets', ['$scope', '$http', function($scope, $http) { var search = 'gdg'; var url = 'http://search.twitter.com/search.json?q=' + search; $http({ method: 'GET', url: url }). success(function(data, status, headers, config) { $scope.tweets = data.results; }). error(function(data, status, headers, config) { console.log('Error: fetch tweets'); $scope.tweets = {}; }); return $scope; }]);
  • 15. Dependency Injection (also know as Inversion of Control) Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its dependencies.
  • 16. Services Angular services are singletons that carry out specific tasks. Eg. $http service that provides low level access to the browser's XMLHttpRequest object.
  • 17. gdgApp.controller('getTweets', ['$scope', '$http', function($scope, $http) { // ... return $scope; }]); angular.module('gdgModuleAlarm', []). factory('alarm', function($window) { return { alarm: function(text) { $window.alert(text); } }; } );
  • 18. Injectors // New injector created from the previus declared module. var injector = angular.injector(['gdgModuleAlarm', 'ng']); // Request any dependency from the injector var a = injector.get('alarm'); // We can also force injecting using var alarmFactory = function (my$window) {}; alarmFactory.$inject = ['$window'];
  • 19. Filters Filters perform data transformation. They follow the spirit of UNIX filters and use similar syntax | (pipe).
  • 20. <!doctype html> <html ng-app> <head> <script src="js/angular.min.js" ></script> <script src="js/demo.js" ></script> </head> <body> <a href="" ng-click="predicate = 'members'; reverse=!reverse"<Sort</a> <ul ng-controller="getGdgList"> <li ng-repeat="gdg in gdgs | orderBy:predicate:reverse "> have members </ul> </body> </html>
  • 21. Sort GDG MILAN have 92 members GDG BARCELONA have 228 members GDG SILICON VALLEY have 171 members GDG STOCKHOLM have 119 members GDG HERZELIYA have 140 members GDG AHMEDABAD have 78 members GDG LAGOS have 115 members GDG BANGALORE have 109 members GDG LIMA have 175 members GDG L-AB have 77 members
  • 22. Creating custom filters angular.module('agaveeApp', []) .filter('orderByVersion', function() { return function(modules, version) { var parseVersionString = function (str) { /* .. */ }; var vMinMet = function(vmin, vcurrent) { /* .. */ }; var result = []; for (var i = 0; i < modules.length; i++) { if (vMinMet(modules[i].version_added, version)) { result[result.length] = modules[i]; } } return result; }; });
  • 23. Model The model is the data which is merged with the template to produce the view.
  • 24. <!doctype html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js" </head> <body> <div> <input type="text" ng-model="sample" placeholder="Enter text"> <hr> <h1>!</h1> </div> </body> </html>
  • 25. Configuration angular.module('gdgApp', []) .constant('gdg', { 'url' : 'http://localhost:3000', 'token': 'e9adf82fd1cb716548ef1d4621a5935dcf869817' }) // Configure $http .config(['$httpProvider', 'gdg', function ($httpProvider, gdg) { $httpProvider.defaults.headers.common['X-gdg-API-Key'] = gdg.token; } ]);
  • 26. Routing angular.module('gdgApp', []) // Configure services .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/projects', { templateUrl: 'views/projects.html', controller: 'ProjectsCtrl' }); $routeProvider.when('/projects/:project', { templateUrl: 'views/project.html', controller: 'ProjectCtrl' }); $routeProvider.otherwise({redirectTo: '/projects'}); }]);
  • 27. Resource angular.module('resources.project', ['ngResource']) .factory('Project', ['$http', '$resource', 'gdg', function ($http, gdg) { return $resource(gdg.url + '/project/:projectId', {projectId:'@id'}, { query : { method : 'GET', isArray:true}, create : { method : 'POST' }, save : { method : 'PUT' }, delete : { method : 'DELETE' } }); }]); // ... var p = new Project(); p.name = 'GDG Milan'; p.$save();
  • 28. angular.module('resources.project', ['ngResource']) .factory('Project', ['$http', 'gdg', function ($http, gdg) { var Project = function (data) { angular.extend(this, data); }; // a static method to retrieve Project by ID Project.get = function (id) { return $http.get(gdg.url + '/projects/' + id).then(function (response) { return new Project(response.data); }); }; // an instance method to create a new Project Project.prototype.create = function () { var project = this; return $http.post(gdg.url + '/projects.json', project).then(function (response) project.id = response.data.id;
  • 29. Testing Karma - a test runner that fits all our needs. Jasmine - Jasmine is a behavior-driven development framework for testing JavaScript code.
  • 30. describe('Controller: getGdgList', function () { // load the controller's module beforeEach(module('gdgApp')); var getGdgList, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller) { scope = {}; getGdgList = $controller('getGdgList', { $scope: scope }); })); it('GDG List must display defined number of items', function () { expect(scope.gdgs.length).toBe(10); });
  • 31. Angular 1.2 ...is coming! More modular Introduce ng-animate (and related) Support to mobile (÷/-)
  • 32. Demo
  • 34. THE END Marco Vito Moscaritolo / @mavimo