SlideShare a Scribd company logo
AngularJs
AmasterdamJs 24 April 2013
Who am I?
● Marcin Wosinek
● 5 years IT experience
- WebDev: Javascript
- C# dev: UnitTests
● Currently js contractor in Poznan, Poland
jQuery
You?
Topic
New reality
Traditional web architecture
Server
Client
html +
data
request
Application approach
Server
Client
js
template
RESTdata
Communication with backend
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
}
}
Changes
Challenges - testability
function PasswordCtrl() {
var msg = $('.ex1 span');
var input = $('.ex1 input');
var strength;
this.grade = function() {
msg.removeClass(strength);
var pwd = input.val();
password.text(pwd);
if (pwd.length > 8) {
strength = 'strong';
}
else {
strength = 'weak';
}
msg
.addClass(strength)
.text(strength);
Challenges - boilerplate
initialize: function () {
this.allCheckbox = this.$('#toggle-all')[0];
this.$input = this.$('#new-todo');
this.$footer = this.$('#footer');
this.$main = this.$('#main');
this.listenTo(app.Todos ,'add',this.addOne);
this.listenTo(app.Todos, 'reset', this.addAll);
this.listenTo(app.Todos, 'change:completed', this.
filterOne);
this.listenTo(app.Todos, 'filter', this.filterAll);
this.listenTo(app.Todos, 'all', this.render);
app.Todos.fetch();
}
AngularJs
MV* Architecture
ViewModel
View Model
Shared with backend
$scope
Angular html
AngularJs core
Controller
View
<ul>
<li ng-repeat="todo in todos">
<span></span>
</li>
</ul>
<form ng-submit="addTodo()">
<input ng-model="todoText" />
<input type="submit" value="add" />
</form>
Filters
<ul>
<li ng-repeat="project in projects |
filter:search | orderBy:'name'">
<a href=""></a>:
</li>
</ul>
Controller
$scope
presentation
Plain JS objects
// Backbone
app.Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false }
});
// Ember
Todos.Todo = DS.Model.extend({
title: DS.attr('string'),
isCompleted: DS.attr('boolean') });
// Angular
todos.push({
title: $scope.newTodo,
completed: false });
Two ways binding
Web form support
presentation
<!-- Html updated by angular -->
<form name="exampleForm" class="ng-pristine ng-invalid
ng-invalid-required">
Required field:
<input ng-model="required" required="" class="ng-
pristine
ng-invalid ng-invalid-required"></label> <br>
Email field:
<input ng-model="email" type="email" class="ng-pristine
ng-valid ng-valid-email"></label> <br>
<button ng-disabled="!exampleForm.$valid"
disabled="disabled">Submit</button>
</form>
Dependency injection
function HelloCtrl($scope, $window, $log) {
$scope.message = 'Display me in view';
$window.alert('Use window via $window service - that
improves testability');
$log.log('We can even test console log calls - thats to
$log wrapper');
}
Services
// Services that persists and retrieves ToDos from
// localStorage
todomvc.factory('todoStorage', function () {
var STORAGE_ID = 'todos-angularjs';
return {
get: function () {
return JSON
.parse(localStorage.getItem(STORAGE_ID) || '[]');
},
put: function (todos) {
localStorage
.setItem(STORAGE_ID, JSON.stringify(todos));
}};});
Routing - $routeProvider
angular.module('phonecat', [])
.config(['$routeProvider',
function($routeProvider, $locationProvider) {
// $locationProvider.html5Mode(true);
$routeProvider
.when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: PhoneListCtrl
})
.when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: PhoneDetailCtrl
})
.otherwise({
redirectTo: '/phones'
});}]);
REST - $resource
myApp.factory('ProductService', function($resource) {
var ProductResource = $resource('/product/:productId')
, ProductService = {};
ProductService.getItem = function (index) {
return ProductResource.get({productId: index});}
ProductService.addItem = function (item) {
ProductResource.save({}, item));}
return ProductService;
});
function ProductCtrl($scope, ProductService) {
// Take products form ProductService and put it on
$scope
}
Directives
<ANY class="ng-show: {expression};">
<ANY ng-show="{expression}">
<ANY class="ng-hide: {expression};">
<ANY ng-hide="{expression}">
<ng-view> <any ng-view>
<ANY ng-class="{expression}"> <ANY class="ng-class:
{expression};">
<ANY ng-switch="expression">
<ANY ng-switch-when="matchValue1">...</ANY>
<ANY ng-switch-when="matchValue2">...</ANY>
...
<ANY ng-switch-default>...</ANY>
</ANY>
Yeoman
Karma (Testacular)
Habits
Writing callbacks
Habits
Imperative binding
Habits
Changing DOM in
controller
Gotchas - writing directives
angular.module('blink', [])
.directive('blink', function() {
return {
restrict: 'E',
link: function(scope, elm, attr) {
setInterval(function() {
elm.toggle();
}, parseInt(attr.interval, 10) || 1000);
}
};
});
Gotchas - ng-model in ng-repeat
// Gotcha!
<ul>
<li ng-repeat="item in list">
<input ng-model="item" />
</li>
</ul>
// Work as expected
<ul>
<li ng-repeat="item in list">
<input ng-model="item.name" />
</li>
</ul>
Gotchas - code minification
syngularApp.controller('ProductCtrl', function($scope,
ProductApi) {
// easy but minification unfriendly
});
syngularApp.controller('ProductCtrl', ['$scope',
'ProductApi', function($scope, ProductApi) {
// minification resistant
}]);
Gotchas -
$resource
Gotchas - filters working only on arrays
filter
orderBy
Gotchas -
e2e?
Gotchas - updating data from
outside angular
$digest
$apply
Gotchas - $ in service names
$
Questions
?
Learning materials
● http://angularjs.org/
● http://egghead.io/
● http://www.youtube.com/user/angularjs
Summary
Contact
● marcin.wosinek@gmail.com
● @MarcinWosinek
● links, slides, notes and (hopefully) video:
http://bit.ly/AngularJs-AmsterdamJS
Credits
● Audience photo: http://www.flickr.com/photos/dougbelshaw/5604047370/in/photostream
● BackboneJs logo: https://github.com/documentcloud/backbone/blob/master/docs/images/backbone.
● Two ways binding: http://docs.angularjs.org/guide/dev_guide.templates.databinding
● http://karma-runner.github.io/0.8/index.html
● http://yeoman.io/

More Related Content

What's hot (17)

PPTX
AngulrJS Overview
Eyal Vardi
 
PDF
Utilizing Bluebird Promises
Nicholas van de Walle
 
PDF
Google App Engine Developer - Day3
Simon Su
 
PDF
Couchdb
Brian Smith
 
PDF
«От экспериментов с инфраструктурой до внедрения в продакшен»​
FDConf
 
PPTX
Mongoose and MongoDB 101
Will Button
 
DOC
Object oriented mysqli connection function
clickon2010
 
PPTX
Knockout.js
Vivek Rajan
 
PDF
jQuery secrets
Bastian Feder
 
PDF
C++ Programming - 8th Study
Chris Ohk
 
PDF
Databinding and Performance-Tuning in Angular 2
Manfred Steyer
 
PPTX
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Codemotion
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PDF
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 
PDF
MySQL 8.0 Preview: What Is Coming?
Gabriela Ferrara
 
PDF
C++ Programming - 6th Study
Chris Ohk
 
PPTX
Dwr explanation
Arun Maharana
 
AngulrJS Overview
Eyal Vardi
 
Utilizing Bluebird Promises
Nicholas van de Walle
 
Google App Engine Developer - Day3
Simon Su
 
Couchdb
Brian Smith
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
FDConf
 
Mongoose and MongoDB 101
Will Button
 
Object oriented mysqli connection function
clickon2010
 
Knockout.js
Vivek Rajan
 
jQuery secrets
Bastian Feder
 
C++ Programming - 8th Study
Chris Ohk
 
Databinding and Performance-Tuning in Angular 2
Manfred Steyer
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Codemotion
 
Practical Use of MongoDB for Node.js
async_io
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 
MySQL 8.0 Preview: What Is Coming?
Gabriela Ferrara
 
C++ Programming - 6th Study
Chris Ohk
 
Dwr explanation
Arun Maharana
 

Viewers also liked (20)

PDF
El procesador
andrea oncehex
 
PPTX
Cancer de ovario mi parte
Mancho Suarez
 
PDF
Nilla Recommendation Letter
Robert Kodingo
 
PDF
EdicióN13
ciudad comuna
 
PPT
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
mrtncz
 
PDF
Migraña y discapacidad.
José María
 
PDF
ManageEngine ServiceDesk Plus Admin Guide
ServiceDesk Plus
 
PDF
Growth Hacking with LinkedIn - By Peter Chee @thinkspace
Peter Chee
 
PDF
Workshop Webtools
Steffen Büffel
 
PDF
Apresentação OMG! (Interdesigners 2011)
Caio Henrique
 
PPT
Presentación Increventia
CIT Marbella
 
DOCX
CAPITULO II
26200926
 
PPTX
El naixement del món modern reforma
Raquel Pérez Badia
 
PDF
Content Scope España 2015
Arena Media España
 
PDF
House101
Hi House
 
PPTX
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
Steven Clift
 
PDF
Input (warm up)
ashtic
 
PPTX
Thomas Alva Edison
jclua1234
 
PDF
Brochure on Training , Courses & other HR Services
Nizufer Ansari
 
El procesador
andrea oncehex
 
Cancer de ovario mi parte
Mancho Suarez
 
Nilla Recommendation Letter
Robert Kodingo
 
EdicióN13
ciudad comuna
 
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
mrtncz
 
Migraña y discapacidad.
José María
 
ManageEngine ServiceDesk Plus Admin Guide
ServiceDesk Plus
 
Growth Hacking with LinkedIn - By Peter Chee @thinkspace
Peter Chee
 
Workshop Webtools
Steffen Büffel
 
Apresentação OMG! (Interdesigners 2011)
Caio Henrique
 
Presentación Increventia
CIT Marbella
 
CAPITULO II
26200926
 
El naixement del món modern reforma
Raquel Pérez Badia
 
Content Scope España 2015
Arena Media España
 
House101
Hi House
 
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
Steven Clift
 
Input (warm up)
ashtic
 
Thomas Alva Edison
jclua1234
 
Brochure on Training , Courses & other HR Services
Nizufer Ansari
 
Ad

Similar to Angular js 24 april 2013 amsterdamjs (20)

PDF
Data models in Angular 1 & 2
Adam Klein
 
PPTX
Angular Workshop_Sarajevo2
Christoffer Noring
 
PPTX
Getting Started with Angular JS
Akshay Mathur
 
PDF
AngularJS Basics with Example
Sergey Bolshchikov
 
PDF
Pengenalan AngularJS
Edi Santoso
 
PDF
Mini-Training: AngularJS
Betclic Everest Group Tech Team
 
PPTX
Angular js for enteprise application
vu van quyet
 
PDF
How Angular2 Can Improve Your AngularJS Apps Today!
Nir Kaufman
 
PDF
Design strategies for AngularJS
SmartOrg
 
PPT
AngularJS and SPA
Lorenzo Dematté
 
PPTX
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
PDF
Angular2 workshop
Nir Kaufman
 
PDF
AngularJS: The Bridge Between Today and Tomorrow's Web (Todd Motto)
Future Insights
 
PPTX
AngularJS One Day Workshop
Shyam Seshadri
 
PPTX
The future of web development write once, run everywhere with angular.js and ...
Mark Roden
 
PDF
The future of web development write once, run everywhere with angular js an...
Mark Leusink
 
PDF
How to build an AngularJS backend-ready app WITHOUT BACKEND
Enrique Oriol Bermúdez
 
PPTX
Basics of AngularJS
Filip Janevski
 
PPTX
A different thought angular js part-3
Amit Thakkar
 
PDF
FITC presents: Mobile & offline data synchronization in Angular JS
FITC
 
Data models in Angular 1 & 2
Adam Klein
 
Angular Workshop_Sarajevo2
Christoffer Noring
 
Getting Started with Angular JS
Akshay Mathur
 
AngularJS Basics with Example
Sergey Bolshchikov
 
Pengenalan AngularJS
Edi Santoso
 
Mini-Training: AngularJS
Betclic Everest Group Tech Team
 
Angular js for enteprise application
vu van quyet
 
How Angular2 Can Improve Your AngularJS Apps Today!
Nir Kaufman
 
Design strategies for AngularJS
SmartOrg
 
AngularJS and SPA
Lorenzo Dematté
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Angular2 workshop
Nir Kaufman
 
AngularJS: The Bridge Between Today and Tomorrow's Web (Todd Motto)
Future Insights
 
AngularJS One Day Workshop
Shyam Seshadri
 
The future of web development write once, run everywhere with angular.js and ...
Mark Roden
 
The future of web development write once, run everywhere with angular js an...
Mark Leusink
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
Enrique Oriol Bermúdez
 
Basics of AngularJS
Filip Janevski
 
A different thought angular js part-3
Amit Thakkar
 
FITC presents: Mobile & offline data synchronization in Angular JS
FITC
 
Ad

More from Marcin Wosinek (7)

PDF
Automation in angular js
Marcin Wosinek
 
PDF
Automatyzacja w ng świecie - ng-poznań 11 września 2014
Marcin Wosinek
 
PDF
AngularJs in Las Palmas de GC
Marcin Wosinek
 
PDF
The angular way 19 october 2013 Gdańsk
Marcin Wosinek
 
PDF
Angular js warsztaty stopień 2
Marcin Wosinek
 
PDF
Angular js warsztaty stopień 1
Marcin Wosinek
 
PDF
Backbone js in drupal core
Marcin Wosinek
 
Automation in angular js
Marcin Wosinek
 
Automatyzacja w ng świecie - ng-poznań 11 września 2014
Marcin Wosinek
 
AngularJs in Las Palmas de GC
Marcin Wosinek
 
The angular way 19 october 2013 Gdańsk
Marcin Wosinek
 
Angular js warsztaty stopień 2
Marcin Wosinek
 
Angular js warsztaty stopień 1
Marcin Wosinek
 
Backbone js in drupal core
Marcin Wosinek
 

Angular js 24 april 2013 amsterdamjs

  • 2. Who am I? ● Marcin Wosinek ● 5 years IT experience - WebDev: Javascript - C# dev: UnitTests ● Currently js contractor in Poznan, Poland
  • 9. Communication with backend { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 } }
  • 11. Challenges - testability function PasswordCtrl() { var msg = $('.ex1 span'); var input = $('.ex1 input'); var strength; this.grade = function() { msg.removeClass(strength); var pwd = input.val(); password.text(pwd); if (pwd.length > 8) { strength = 'strong'; } else { strength = 'weak'; } msg .addClass(strength) .text(strength);
  • 12. Challenges - boilerplate initialize: function () { this.allCheckbox = this.$('#toggle-all')[0]; this.$input = this.$('#new-todo'); this.$footer = this.$('#footer'); this.$main = this.$('#main'); this.listenTo(app.Todos ,'add',this.addOne); this.listenTo(app.Todos, 'reset', this.addAll); this.listenTo(app.Todos, 'change:completed', this. filterOne); this.listenTo(app.Todos, 'filter', this.filterAll); this.listenTo(app.Todos, 'all', this.render); app.Todos.fetch(); }
  • 14. MV* Architecture ViewModel View Model Shared with backend $scope Angular html AngularJs core Controller
  • 15. View <ul> <li ng-repeat="todo in todos"> <span></span> </li> </ul> <form ng-submit="addTodo()"> <input ng-model="todoText" /> <input type="submit" value="add" /> </form>
  • 16. Filters <ul> <li ng-repeat="project in projects | filter:search | orderBy:'name'"> <a href=""></a>: </li> </ul>
  • 19. Plain JS objects // Backbone app.Todo = Backbone.Model.extend({ defaults: { title: '', completed: false } }); // Ember Todos.Todo = DS.Model.extend({ title: DS.attr('string'), isCompleted: DS.attr('boolean') }); // Angular todos.push({ title: $scope.newTodo, completed: false });
  • 21. Web form support presentation <!-- Html updated by angular --> <form name="exampleForm" class="ng-pristine ng-invalid ng-invalid-required"> Required field: <input ng-model="required" required="" class="ng- pristine ng-invalid ng-invalid-required"></label> <br> Email field: <input ng-model="email" type="email" class="ng-pristine ng-valid ng-valid-email"></label> <br> <button ng-disabled="!exampleForm.$valid" disabled="disabled">Submit</button> </form>
  • 22. Dependency injection function HelloCtrl($scope, $window, $log) { $scope.message = 'Display me in view'; $window.alert('Use window via $window service - that improves testability'); $log.log('We can even test console log calls - thats to $log wrapper'); }
  • 23. Services // Services that persists and retrieves ToDos from // localStorage todomvc.factory('todoStorage', function () { var STORAGE_ID = 'todos-angularjs'; return { get: function () { return JSON .parse(localStorage.getItem(STORAGE_ID) || '[]'); }, put: function (todos) { localStorage .setItem(STORAGE_ID, JSON.stringify(todos)); }};});
  • 24. Routing - $routeProvider angular.module('phonecat', []) .config(['$routeProvider', function($routeProvider, $locationProvider) { // $locationProvider.html5Mode(true); $routeProvider .when('/phones', { templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl }) .when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl }) .otherwise({ redirectTo: '/phones' });}]);
  • 25. REST - $resource myApp.factory('ProductService', function($resource) { var ProductResource = $resource('/product/:productId') , ProductService = {}; ProductService.getItem = function (index) { return ProductResource.get({productId: index});} ProductService.addItem = function (item) { ProductResource.save({}, item));} return ProductService; }); function ProductCtrl($scope, ProductService) { // Take products form ProductService and put it on $scope }
  • 26. Directives <ANY class="ng-show: {expression};"> <ANY ng-show="{expression}"> <ANY class="ng-hide: {expression};"> <ANY ng-hide="{expression}"> <ng-view> <any ng-view> <ANY ng-class="{expression}"> <ANY class="ng-class: {expression};"> <ANY ng-switch="expression"> <ANY ng-switch-when="matchValue1">...</ANY> <ANY ng-switch-when="matchValue2">...</ANY> ... <ANY ng-switch-default>...</ANY> </ANY>
  • 32. Gotchas - writing directives angular.module('blink', []) .directive('blink', function() { return { restrict: 'E', link: function(scope, elm, attr) { setInterval(function() { elm.toggle(); }, parseInt(attr.interval, 10) || 1000); } }; });
  • 33. Gotchas - ng-model in ng-repeat // Gotcha! <ul> <li ng-repeat="item in list"> <input ng-model="item" /> </li> </ul> // Work as expected <ul> <li ng-repeat="item in list"> <input ng-model="item.name" /> </li> </ul>
  • 34. Gotchas - code minification syngularApp.controller('ProductCtrl', function($scope, ProductApi) { // easy but minification unfriendly }); syngularApp.controller('ProductCtrl', ['$scope', 'ProductApi', function($scope, ProductApi) { // minification resistant }]);
  • 36. Gotchas - filters working only on arrays filter orderBy
  • 38. Gotchas - updating data from outside angular $digest $apply
  • 39. Gotchas - $ in service names $
  • 41. Learning materials ● http://angularjs.org/ ● http://egghead.io/ ● http://www.youtube.com/user/angularjs
  • 43. Contact ● [email protected] ● @MarcinWosinek ● links, slides, notes and (hopefully) video: http://bit.ly/AngularJs-AmsterdamJS
  • 44. Credits ● Audience photo: http://www.flickr.com/photos/dougbelshaw/5604047370/in/photostream ● BackboneJs logo: https://github.com/documentcloud/backbone/blob/master/docs/images/backbone. ● Two ways binding: http://docs.angularjs.org/guide/dev_guide.templates.databinding ● http://karma-runner.github.io/0.8/index.html ● http://yeoman.io/