SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
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/

Weitere ähnliche Inhalte

Was ist angesagt?

AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS OverviewEyal Vardi
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​FDConf
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101Will Button
 
Object oriented mysqli connection function
Object oriented mysqli connection functionObject oriented mysqli connection function
Object oriented mysqli connection functionclickon2010
 
C++ Programming - 8th Study
C++ Programming - 8th StudyC++ Programming - 8th Study
C++ Programming - 8th StudyChris Ohk
 
Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Manfred Steyer
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Codemotion
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?Gabriela Ferrara
 
C++ Programming - 6th Study
C++ Programming - 6th StudyC++ Programming - 6th Study
C++ Programming - 6th StudyChris Ohk
 

Was ist angesagt? (17)

AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
Utilizing Bluebird Promises
Utilizing Bluebird PromisesUtilizing Bluebird Promises
Utilizing Bluebird Promises
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Couchdb
CouchdbCouchdb
Couchdb
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
 
Object oriented mysqli connection function
Object oriented mysqli connection functionObject oriented mysqli connection function
Object oriented mysqli connection function
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
C++ Programming - 8th Study
C++ Programming - 8th StudyC++ Programming - 8th Study
C++ Programming - 8th Study
 
Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?
 
C++ Programming - 6th Study
C++ Programming - 6th StudyC++ Programming - 6th Study
C++ Programming - 6th Study
 
Dwr explanation
Dwr explanationDwr explanation
Dwr explanation
 

Andere mochten auch

Cancer de ovario mi parte
Cancer de ovario mi parteCancer de ovario mi parte
Cancer de ovario mi parteMancho Suarez
 
Nilla Recommendation Letter
Nilla Recommendation LetterNilla Recommendation Letter
Nilla Recommendation LetterRobert Kodingo
 
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT LeipzigPerspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzigmrtncz
 
Migraña y discapacidad.
Migraña y discapacidad.Migraña y discapacidad.
Migraña y discapacidad.José María
 
ManageEngine ServiceDesk Plus Admin Guide
ManageEngine ServiceDesk Plus Admin GuideManageEngine ServiceDesk Plus Admin Guide
ManageEngine ServiceDesk Plus Admin GuideServiceDesk Plus
 
Growth Hacking with LinkedIn - By Peter Chee @thinkspace
Growth Hacking with LinkedIn - By Peter Chee @thinkspaceGrowth Hacking with LinkedIn - By Peter Chee @thinkspace
Growth Hacking with LinkedIn - By Peter Chee @thinkspacePeter Chee
 
Apresentação OMG! (Interdesigners 2011)
Apresentação OMG! (Interdesigners 2011)Apresentação OMG! (Interdesigners 2011)
Apresentação OMG! (Interdesigners 2011)Caio Henrique
 
Presentación Increventia
Presentación IncreventiaPresentación Increventia
Presentación IncreventiaCIT Marbella
 
CAPITULO II
CAPITULO IICAPITULO II
CAPITULO II26200926
 
El naixement del món modern reforma
El naixement del món modern reformaEl naixement del món modern reforma
El naixement del món modern reformaRaquel Pérez Badia
 
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.orgOnline Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.orgSteven Clift
 
Input (warm up)
Input (warm up)Input (warm up)
Input (warm up)ashtic
 
Thomas Alva Edison
Thomas Alva EdisonThomas Alva Edison
Thomas Alva Edisonjclua1234
 
Brochure on Training , Courses & other HR Services
Brochure on Training , Courses & other HR Services Brochure on Training , Courses & other HR Services
Brochure on Training , Courses & other HR Services Nizufer Ansari
 

Andere mochten auch (20)

El procesador
El procesadorEl procesador
El procesador
 
Cancer de ovario mi parte
Cancer de ovario mi parteCancer de ovario mi parte
Cancer de ovario mi parte
 
Nilla Recommendation Letter
Nilla Recommendation LetterNilla Recommendation Letter
Nilla Recommendation Letter
 
EdicióN13
EdicióN13EdicióN13
EdicióN13
 
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT LeipzigPerspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
Perspektivwechsel Normdaten: ein neues Nutzungskonzept an der UB und HMT Leipzig
 
Migraña y discapacidad.
Migraña y discapacidad.Migraña y discapacidad.
Migraña y discapacidad.
 
ManageEngine ServiceDesk Plus Admin Guide
ManageEngine ServiceDesk Plus Admin GuideManageEngine ServiceDesk Plus Admin Guide
ManageEngine ServiceDesk Plus Admin Guide
 
Growth Hacking with LinkedIn - By Peter Chee @thinkspace
Growth Hacking with LinkedIn - By Peter Chee @thinkspaceGrowth Hacking with LinkedIn - By Peter Chee @thinkspace
Growth Hacking with LinkedIn - By Peter Chee @thinkspace
 
Workshop Webtools
Workshop WebtoolsWorkshop Webtools
Workshop Webtools
 
Apresentação OMG! (Interdesigners 2011)
Apresentação OMG! (Interdesigners 2011)Apresentação OMG! (Interdesigners 2011)
Apresentação OMG! (Interdesigners 2011)
 
Presentación Increventia
Presentación IncreventiaPresentación Increventia
Presentación Increventia
 
CAPITULO II
CAPITULO IICAPITULO II
CAPITULO II
 
Aparato psiquico
Aparato psiquicoAparato psiquico
Aparato psiquico
 
El naixement del món modern reforma
El naixement del món modern reformaEl naixement del món modern reforma
El naixement del món modern reforma
 
Content Scope España 2015
Content Scope España 2015 Content Scope España 2015
Content Scope España 2015
 
House101
House101House101
House101
 
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.orgOnline Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
Online Communities at EuroPCom - Steven Clift KHub.Net and E-Democracy.org
 
Input (warm up)
Input (warm up)Input (warm up)
Input (warm up)
 
Thomas Alva Edison
Thomas Alva EdisonThomas Alva Edison
Thomas Alva Edison
 
Brochure on Training , Courses & other HR Services
Brochure on Training , Courses & other HR Services Brochure on Training , Courses & other HR Services
Brochure on Training , Courses & other HR Services
 

Ähnlich wie Angular js 24 april 2013 amsterdamjs

Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013Laurent_VB
 
How to Hack a Road Trip with a Webcam, a GSP and Some Fun with Node
How to Hack a Road Trip  with a Webcam, a GSP and Some Fun with NodeHow to Hack a Road Trip  with a Webcam, a GSP and Some Fun with Node
How to Hack a Road Trip with a Webcam, a GSP and Some Fun with Nodepdeschen
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]JavaScript Meetup HCMC
 
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 KarmaExoLeaders.com
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile servicesAymeric Weinbach
 
Introduction to Angular js
Introduction to Angular jsIntroduction to Angular js
Introduction to Angular jsMustafa Gamal
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)Domenic Denicola
 
TestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergTestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergXebia Nederland BV
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
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 JavaScriptGuy Royse
 
0 to App faster with NodeJS and Ruby
0 to App faster with NodeJS and Ruby0 to App faster with NodeJS and Ruby
0 to App faster with NodeJS and RubyRebecca Mills
 
Cassandra Day Chicago 2015: 0 to App Faster with Node.js and Ruby
Cassandra Day Chicago 2015: 0 to App Faster with Node.js and RubyCassandra Day Chicago 2015: 0 to App Faster with Node.js and Ruby
Cassandra Day Chicago 2015: 0 to App Faster with Node.js and RubyDataStax Academy
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 

Ähnlich wie Angular js 24 april 2013 amsterdamjs (20)

Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
How to Hack a Road Trip with a Webcam, a GSP and Some Fun with Node
How to Hack a Road Trip  with a Webcam, a GSP and Some Fun with NodeHow to Hack a Road Trip  with a Webcam, a GSP and Some Fun with Node
How to Hack a Road Trip with a Webcam, a GSP and Some Fun with Node
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
 
NoSQL meets Microservices
NoSQL meets MicroservicesNoSQL meets Microservices
NoSQL meets Microservices
 
AngularJS On-Ramp
AngularJS On-RampAngularJS On-Ramp
AngularJS On-Ramp
 
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
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile services
 
Introduction to Angular js
Introduction to Angular jsIntroduction to Angular js
Introduction to Angular js
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
TestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike WoudenbergTestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
TestWorks conf Dry up your angularjs unit tests using mox - Mike Woudenberg
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
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
 
0 to App faster with NodeJS and Ruby
0 to App faster with NodeJS and Ruby0 to App faster with NodeJS and Ruby
0 to App faster with NodeJS and Ruby
 
Cassandra Day Chicago 2015: 0 to App Faster with Node.js and Ruby
Cassandra Day Chicago 2015: 0 to App Faster with Node.js and RubyCassandra Day Chicago 2015: 0 to App Faster with Node.js and Ruby
Cassandra Day Chicago 2015: 0 to App Faster with Node.js and Ruby
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Postman On Steroids
Postman On SteroidsPostman On Steroids
Postman On Steroids
 

Mehr von Marcin Wosinek

Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular jsMarcin Wosinek
 
Automatyzacja w ng świecie - ng-poznań 11 września 2014
Automatyzacja w ng świecie - ng-poznań 11 września 2014Automatyzacja w ng świecie - ng-poznań 11 września 2014
Automatyzacja w ng świecie - ng-poznań 11 września 2014Marcin Wosinek
 
AngularJs in Las Palmas de GC
AngularJs in Las Palmas de GCAngularJs in Las Palmas de GC
AngularJs in Las Palmas de GCMarcin Wosinek
 
The angular way 19 october 2013 Gdańsk
The angular way   19 october 2013 GdańskThe angular way   19 october 2013 Gdańsk
The angular way 19 october 2013 GdańskMarcin Wosinek
 
Angular js warsztaty stopień 2
Angular js   warsztaty stopień 2Angular js   warsztaty stopień 2
Angular js warsztaty stopień 2Marcin Wosinek
 
Angular js warsztaty stopień 1
Angular js   warsztaty stopień 1Angular js   warsztaty stopień 1
Angular js warsztaty stopień 1Marcin Wosinek
 

Mehr von Marcin Wosinek (6)

Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
 
Automatyzacja w ng świecie - ng-poznań 11 września 2014
Automatyzacja w ng świecie - ng-poznań 11 września 2014Automatyzacja w ng świecie - ng-poznań 11 września 2014
Automatyzacja w ng świecie - ng-poznań 11 września 2014
 
AngularJs in Las Palmas de GC
AngularJs in Las Palmas de GCAngularJs in Las Palmas de GC
AngularJs in Las Palmas de GC
 
The angular way 19 october 2013 Gdańsk
The angular way   19 october 2013 GdańskThe angular way   19 october 2013 Gdańsk
The angular way 19 october 2013 Gdańsk
 
Angular js warsztaty stopień 2
Angular js   warsztaty stopień 2Angular js   warsztaty stopień 2
Angular js warsztaty stopień 2
 
Angular js warsztaty stopień 1
Angular js   warsztaty stopień 1Angular js   warsztaty stopień 1
Angular js warsztaty stopień 1
 

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 ● marcin.wosinek@gmail.com ● @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/