ANGULARJS

Russian Rebouças

Front End Developer

http://goo.gl/XwcMr6

AGENDA

História

Arquitetura

Scope

Diretivas

Bootstraping

Data-Binding

Dependency Injection

Services

Routes

Ajax

Miško Hevery

Adam Abrons

2009

Feedback

  • Era difícil adicionar novas funcionalidades
  • +17.000 Linhas de Código
  • Difícil de Modificar
  • Difícil de Testar

Brad Green

Engineering Director

Gerente de Projeto do Google Feedback

Aposto que consigo refazer tudo com meu novo Framework em apenas duas semanas! :)

Ele perdeu :(

  • Ele terminou em 3 semanas
  • de 17.000 para 1.500 Linhas
  • Todas as funcionalidades Modulares
  • Reutilizáveis
  • Testáveis

WOOOW

MVW!!

MVC?

MVP?

MVVM?

I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

VIEW

CONTROLLER

scope

hands on!


  angular.module('HelloWorld', [])

  angular.module('HelloWorld')
    .controller('MyController', function($scope) {
      $scope.message = "Hello World!";
    })
  <!DOCTYPE html>
  <html ng-app="HelloWorld">
    <head>
      <title>Hello World</title>
      <script src="path/to/angular.js"></script>
    </head>
    <body ng-controller="MyController">
      <h1>{{message}}</h1>
    </body>
  </html>

DIRETIVAS

  <li ng-repeat="item in items"> 
    {{item.name}} 
  </li>
  <flex-calendar
    options="calendarOptions" 
    events="calendarEvents">
  </flex-calendar>
  <form name="movie">
    <input ng-model="title">
    <input ng-model="director">
    ...
  </form>

PROGRAMAÇÃO DECLARATIVA

EXTENDE O HTML

COMPONENTES

DIRETIVAS

NG-APP
NG-CONTROLLER
NG-MODEL
NG-REPEAT
NG-CLICK
NG-BIND
NG-IF
NG-SWITCH
NG-CHANGE
NG-HIDE
NG-SHOW
NG-REPEAT

HANDS ON!

bootstrap

HTML

CSS

JS

DOM

CONTENT

LOADED

ng-app

directives

$watch

$watch

$watch

$watch

VIEW

DIGEST

CYCLE

events

update view

Data Binding e Change detection

Event Loop

Angular Context


  User: <input type="text" ng-model="user" />
  Password: <input type="password" ng-model="pass" />

VIEW

$watch list

0 - USERNAME

1 - PASSWORD

=

2

  .controller('MainCtrl', function($scope) {
    $scope.foo = "Foo";
    $scope.world = "World";
  });

CONTROLLER

$watch list

0 - WORLD

=

1


  <P> Hello, {{ World }} </P>

VIEW

  .controller('MainCtrl', function($scope) {
    $scope.people = [...];
  });

CONTROLLER

$watch list

(2 * 10) + 1

=

21

  <ul>
    <li ng-repeat="person in people">
      {{person.name}} - {{person.age}}
    </li>
  </ul>

VIEW

$DIGEST LOOP

$watch 1

$watch 2

$watch 3

$watch 4

$watch 5

$watch 6

$watch 7

$watch 8

. . .

$watch list

Hey $watch, qual o seu valor?

É 9

Ok, ele mudou?

Não senhor!

Você, Qual o seu valor?

É 'foo'

Houve mudança?

É 'bar'

Bom! Nós temos um DOM a ser atualizado! :D

Nada acontece

$apply

  
  <button ng-click="someFunction()">
  
  <form>
    <input type"email" ng-model="user.email">
    <input type"password" ng-model="user.password">
    <button ng-click="login(user)">
  </form>

  // PSEUDOCODE

  $apply = function(fn) {

    try {

      fn();

    } finally() {

      $digest();

    }

  }
  
  <input type="checkbox" ng-model="value"> Value

$apply

  
  ThirdyPartyApi.foo(param, function(result) {
    $scope.somVariable = result;
  });
  
  ThirdyPartyApi.foo(param, function(result) {
    $scope.$apply(function() {
      $scope.somVariable = result;
    });
  });
  // PSEUDOCODE

  $apply = function(fn) {

    try {

      fn();

    } finally() {

      $digest();

    }

  }

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

MODULES

// Register a Module
angular.module('moduleName',[]);
// Locate a Module
angular.module('moduleName');

MODULE PATTERN

// Register a Module with Dependencies
angular.module('moduleName',['dependency']);

DI

dependency injection

A

B

C

Create A

Create B

Inject   A

Create C

Inject   B


  .controller('MyController', function($scope, $window) {
    $scope.foo = 'bar';
    $scope.height = $window.innerHeight;
  });

  .controller('MyController', ["$scope", "$window", function(scope, window) {
    scope.foo = 'bar';
    scope.height = window.innerHeight;
  }]);


  angular.module('myApp',[])
  .controller('MyController', MyController);

  MyController.$inject = ['$scope', '$window']

  function MyController (scope, window) {
    $scope.foo = 'bar';
    $scope.height = $window.innerHeight;
  }

single responsibility principle

services

services

controllers

services

  • lógica de apresentação

  • lógica de negócios

  • diretamente ligado a uma view

  • independente de views

  • determinam a ui

  • determinam a aplicação

  • únicos e específicos

  • reutilizáveis

  • quais dados mostrar, interações, ui

  • consumo de dados, lógica de negócios reutilizável

FACTORY VS SERVICE VC PROVIDER

FACTORY


  angular.module('App', [])
    .controller('MoviesController', function($scope, Movies) {
      Movies.list()
      .success(function(response){
        $scope.moviesList = response.data;
      })
      .error(function(response) {
        console.log(response);
      })
     
   })

  angular.module('App')
   .factory('Movies', function($http) {
     return {
       list: function() {
         return $http.get('http://example.com/api/movies');
       },
       get: function(id) {
         return $http.get('http://example.com/api/movies/'+id);
       }
     }
   })

F

C

Create F

Create C

Inject   F

SERVICE


  angular.module('App', [])
    .controller('MoviesController', function($scope, Movies) {
      Movies.list()
      .success(function(response){
        $scope.moviesList = response.data;
      })
      .error(function(response) {
        console.log(response);
      })
     
   })

  angular.module('App')
   .factory('Movies', function($http) {
     this.list = function() {
       return $http.get('http://example.com/api/movies');
     }

     this.get = function(id) {
       return $http.get('http://example.com/api/movies/'+id);
     }
   })

S

C

Create S

Create C

Inject   S

PROVIDER


  angular.module('App', [])
    .provider('helloWorld', function() {
   
    this.setName = function(name) {
      this.name = name;
    };

    this.name = 'Default';

    this.$get = function() {
      var name = this.name;
      return {
        sayHello: function() {
          return "Hello, " + name + "!"
        }
      }
    };
  });

ROUTing

ngRouter

myapplication/

View

homeController

home.html

Controller

myapplication/sobre

sobreController

sobre.html

myapplication/contato

contatoController

contato.html

$routeProvider


  angular.module('myApp', ['ngRoute'])
    .config(function($routeProvider) {
      
      $routeProvider
        // Rota para a pagina Inicial
        .when('/', {
          templateUrl : 'pages/home.html',
          controller  : 'HomeController'
        })

        // Rota para a pagina Sobre
        .when('/sobre', {
          templateUrl : 'pages/sobre.html',
          controller  : 'SobreController'
        })

        // Rota para a pagina Contato
        .when('/contato', {
          templateUrl : 'pages/contato.html',
          controller  : 'ContatoController'
        });
    });

ng-view


  <!DOCTYPE html>
  <html ng-app="myApp">
    <head>
      <title>NgRoute</title>
      <script src="path/to/angular.js"></script>
    </head>
    <body>
      <div ng-view>
        <!-- Aqui é onde as views serão renderizadas -->
      </div>
    </body>
  </html>

ajax

$http


  $http.get('http://exampel.com/api/movies')

  $http.post('http://example.com/api/movie')

  $http.put('http://example.com/api/movie/1')

  $http.patch('http://example.com/api/movie/1')

  $http.delete('http://example.com/api/movie/1')

$http


  $http.get('http://example.com/api/movies')
  .then(function(response){
    $scope.movies = response.data;
  })
  .catch(function(response){
    BeautifulAlert('Ops! Tivemos um probl...');
  })

obrigado!

Made with Slides.com