Wednesday, March 11, 2015

Notes: John Papa - 10 AngularJS Patterns (Codes on the Beach 2014)

BE CONSISTENT!

1. Structure Patterns
    1) By Type:
        app/
              controllers/
              services/
              views/
              factories/
              directives/
      2)By Feature
         app/
               dashboard/
               layout/
               people/
               services/
               Speakers/
               Tracks/
               Sessions
       3) Somewhere in the middle
    LIFT
2. Data Patterns
    Separation of Concerns
    Don't put data access in the Controller
3. Decorate the $exceptionHandler Service
4.  Modularity
    Each module can be app, service or widgets
    Modules are containers
    Defining a Module:

    set a module
var app = angular.module('myApp',[]);

    get a module
var app = angular.module('myApp');
 
    inject dependencies into a Module (like a wrapper ):
angular.module('app',[
   'app.avengers',
   'app.dashboard',
   'app.widgets',
   'app.layout'
]);

    Categories of Dependencies:
angular.module('app',[
   //Angular Modules
   'ngRoute',
   //Custome Modules
   'common',
   // 3rd Party Modules
   'ui.bootstrap',
   'breeze.angular'
]);

                        avengers                ngAnimate
ModularApp   dashboard    core    ngRoute
                        widgets                  common
                        layout                     ui-bootstrap

5. Controller pattern
    Controller is like a constructor

angular
    .module('app.avengers')
    .controller('Avenger',Avenger);

// "Classic" $scope syntax
function Avenger($scope){
    $scope.name = 'Captain America';
    $scope.prop = 'shield';
}

// "Controller As" syntax
function Avenger(){
    var vm = this;
    vm.name = 'Captain America';
    vm.prop = 'shield';
}
6. Clean Code
    IIFE(Immediately Invoked Function Expression)
7. Dependency Injection
    Safely Minify Dependencies
 
angular
    .module('app.dashboard')
    .controller('Dashboard',Dashboard);

function Dashboard(common, dataservice){
    // when minified, the common and dataservice may become a and b, which won't be found
}

Safe way 1: Inline Dependency Array
angular
    .module('app.dashboard')
    .controller('Dashboard',['common','dataservice',Dashboard]);
function Dashboard(common, dataservice){
}

Safe way 2: $inject
angular
    .module('app.dashboard')
    .controller('Dashboard',Dashboard);
Dashboard.$inject = ['$q','dataservice','logger'];
function Dashboard($q, dataservice, logger){
}

8. Tasks and Annotations
    Grunt: Configuration over code; File based
    Gulp: Code over configuration; Stream based
9. Breeze, Local Storage, Validation, Karma, Gulp and More

1 comment: