SlideShare a Scribd company logo
1 of 44
Download to read offline
AngularJs
4Developers 12 kwietnia 2013
AngularJs
4Developers 12 kwietnia 2013
Kim jestem?
● Marcin Wosinek
● 5 lat doświadczenia w IT
     - WebDev: Javascript
     - C# dev: UnitTests
● Aktualnie js kontraktor w Poznaniu
Wy?
Temat
Nowa rzeczywistość
Tradycyjna architektura stron


                 Serwer

        html z
                          request
        danymi



                 KLIENT
Podejście aplikacyjne


                  Serwer

          js
                    dane   rest
       template



                  KLIENT
Komunikacja z backendem
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
      "streetAddress": "21 2nd Street",
      "city": "New York",
      "state": "NY",
      "postalCode": 10021
    }
}
Zmiany
Wyzwania - testowalność
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);
Wyzwania - 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
$scope

Architektura MV*                                 Kontroler




                     ViewModel                     Generowane przez
Angularowy html                                        serwisy




              View                            Model


                         AngularJs core
Widok
<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>
Filtry
<ul>
  <li ng-repeat="project in projects |
filter:search | orderBy:'name'">
      <a href=""></a>:
  </li>
</ul>
Kontrolery
$scope
prezentacja
Proste obiekty js
// 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
Wsparcie dla formularza
prezentacja
<!-- 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>
Wstrzykiwanie zależności
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');
}
Serwisy
// 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));
    }};});
Ścieżki - $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'
      });}]);
Komunikacja z backendem - $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)
Nawyki




Pisanie callbacków
Nawyki




bindowanie
Nawyki



Zmienianie DOM w
kontrolerze
Gotchas - pisanie 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 w 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 - minimalizowanie kodu
syngularApp.controller('ProductCtrl', function($scope,
ProductApi) {
  // easy but minification unfriendly
});


syngularApp.controller('ProductCtrl', ['$scope',
'ProductApi', function($scope, ProductApi) {
  // minification resistant
}]);
Gotchas -

       $resource
Gotchas - filtry działające tylko na tablicach


               filter
             orderBy
Gotchas -




e2e?
Gotchas - aktualizowanie scope
spoza frameworka



      $digest
      $apply
Gotchas - $ w nazwach serwisów




            $
Pytania




          ?
Materiały

● http://angularjs.org/
● http://egghead.io/
● http://www.youtube.com/user/angularjs
Podsumowanie
Kontakt
● marcin.wosinek@gmail.com
● @MarcinWosinek
● linki + notatki:
http://bit.ly/4Devs-AngularJs
Podziękowania
●   zdjęcie z publicznością: http://www.flickr.com/photos/dougbelshaw/5604047370/in/photostream
●   logo BackboneJs: 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

What's hot (20)

Modules and injector
Modules and injectorModules and injector
Modules and injector
 
AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
AngularJs
AngularJsAngularJs
AngularJs
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
AngularJS and SPA
AngularJS and SPAAngularJS and SPA
AngularJS and SPA
 

Viewers also liked

Ionic framework - aplikacja mobilna w 15 minut
Ionic framework - aplikacja mobilna w 15 minutIonic framework - aplikacja mobilna w 15 minut
Ionic framework - aplikacja mobilna w 15 minut
Tomasz Borowski
 

Viewers also liked (8)

AngularJS - podstawy
AngularJS - podstawyAngularJS - podstawy
AngularJS - podstawy
 
raise profile
raise profileraise profile
raise profile
 
Grywalizacja rzeczywistości, czyli jak uciec od kompa
Grywalizacja rzeczywistości, czyli jak uciec od kompaGrywalizacja rzeczywistości, czyli jak uciec od kompa
Grywalizacja rzeczywistości, czyli jak uciec od kompa
 
Meteor
MeteorMeteor
Meteor
 
Aplikacje mobilne tworzone w technologiach webowych
Aplikacje mobilne tworzone w technologiach webowychAplikacje mobilne tworzone w technologiach webowych
Aplikacje mobilne tworzone w technologiach webowych
 
Tworzenie niezależnego środowiska do developmentu aplikacji frontendowej
Tworzenie niezależnego środowiska do developmentu aplikacji frontendowejTworzenie niezależnego środowiska do developmentu aplikacji frontendowej
Tworzenie niezależnego środowiska do developmentu aplikacji frontendowej
 
Ionic framework - aplikacja mobilna w 15 minut
Ionic framework - aplikacja mobilna w 15 minutIonic framework - aplikacja mobilna w 15 minut
Ionic framework - aplikacja mobilna w 15 minut
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 

Similar to Angular js - 4developers 12 kwietnia 2013

Angular js 24 april 2013 amsterdamjs
Angular js   24 april 2013 amsterdamjsAngular js   24 april 2013 amsterdamjs
Angular js 24 april 2013 amsterdamjs
Marcin Wosinek
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Introduction to Angular js
Introduction to Angular jsIntroduction to Angular js
Introduction to Angular js
Mustafa Gamal
 

Similar to Angular js - 4developers 12 kwietnia 2013 (20)

Built in filters
Built in filtersBuilt in filters
Built in filters
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
 
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
 
Angular js 24 april 2013 amsterdamjs
Angular js   24 april 2013 amsterdamjsAngular js   24 april 2013 amsterdamjs
Angular js 24 april 2013 amsterdamjs
 
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)
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
 
Pengenalan AngularJS
Pengenalan AngularJSPengenalan AngularJS
Pengenalan AngularJS
 
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
 
[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
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routing
 
Opencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJSOpencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJS
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Angular.js is super cool
Angular.js is super coolAngular.js is super cool
Angular.js is super cool
 
Introduction to Angular js
Introduction to Angular jsIntroduction to Angular js
Introduction to Angular js
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 

More from Marcin Wosinek (7)

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
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 

Angular js - 4developers 12 kwietnia 2013

  • 3. Kim jestem? ● Marcin Wosinek ● 5 lat doświadczenia w IT - WebDev: Javascript - C# dev: UnitTests ● Aktualnie js kontraktor w Poznaniu
  • 4. Wy?
  • 7. Tradycyjna architektura stron Serwer html z request danymi KLIENT
  • 8. Podejście aplikacyjne Serwer js dane rest template KLIENT
  • 9. Komunikacja z backendem { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 } }
  • 11. Wyzwania - testowalność 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. Wyzwania - 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. $scope Architektura MV* Kontroler ViewModel Generowane przez Angularowy html serwisy View Model AngularJs core
  • 15. Widok <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. Filtry <ul> <li ng-repeat="project in projects | filter:search | orderBy:'name'"> <a href=""></a>: </li> </ul>
  • 19. Proste obiekty js // 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. Wsparcie dla formularza prezentacja <!-- 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. Wstrzykiwanie zależności 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. Serwisy // 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. Ścieżki - $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. Komunikacja z backendem - $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 - pisanie 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 w 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 - minimalizowanie kodu syngularApp.controller('ProductCtrl', function($scope, ProductApi) { // easy but minification unfriendly }); syngularApp.controller('ProductCtrl', ['$scope', 'ProductApi', function($scope, ProductApi) { // minification resistant }]);
  • 35. Gotchas - $resource
  • 36. Gotchas - filtry działające tylko na tablicach filter orderBy
  • 38. Gotchas - aktualizowanie scope spoza frameworka $digest $apply
  • 39. Gotchas - $ w nazwach serwisów $
  • 40. Pytania ?
  • 43. Kontakt ● marcin.wosinek@gmail.com ● @MarcinWosinek ● linki + notatki: http://bit.ly/4Devs-AngularJs
  • 44. Podziękowania ● zdjęcie z publicznością: http://www.flickr.com/photos/dougbelshaw/5604047370/in/photostream ● logo BackboneJs: 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/