Controllers & $scope

Advice On Getting into Angular

A Note on "Rules"

All rules are meant to be broken.

 

If you know WHY a rule exists, you can break it well.

"Rule" 1

Controllers should manage interactions of a single "state"

Landing Page Controller

Shopping Page Controller

Checkout Page Controller

Controllers are the main source of complexity in Angular.

 

Keeping our controller scheme simple saves us mental energy

Landing Page Controller

Shopping Page Controller

Checkout Page Controller

Landing Header Ctrl

Landing Form Ctrl

Landing Form Ctrl

Landing State

Shopping Items Ctrl

Shopping Cart  Ctrl

Shopping Filters Ctrl

Checkout Form Ctrl

Checkout Coupon Ctrl

Checkout Upsell Ctrl

Shopping State

Checkout State

Avoid Confusing Controllers

"Rule" 2: Use $scope judiciously

  • $scope is used to expose data and functions to the "view": our HTML.
     
  • Anything on $scope has an expensive "watcher". Too many watchers === slow code
     
  • "Judiciously," means, "as little as possible."

"Rule" 3: $scope is "this" and your controller function is a constructor.

angular.module("app", []).controller("ShoppingController", function($scope) {
    
    // This is your constructor function. 
    // Anything you do here should be bootstrapping
    // The initial state of your app

    // Anything added to the $scope object is available to the view
    $scope.boundValue = "Initial Value for boundValue"; 

});	

"Rule" 4: Be as precise as possible with ng-controller, $scope, and $rootScope

  • $rootScope properties are like global variables -- use if you absolutely must.
     
  • ng-controller should be covering the least amount of HTML it can.

"Rule" 5: Refactoring is part of the deal

As an application grows in size and complexity, Controllers and Services will outgrow their original designs.

 

Expect to break them down into smaller components every so often.

Assets Structure

Angular lends itself to grouping by application vs grouping by
Model / View / Controller

├── assets
│   ├── css
│   ├── images
│   └── js
│       ├── appConstructor.js    // Handles creation of the application (ng-app)
│       ├── checkout             // Everything for the 'checkout' state 
│       │   ├── checkoutController.js
│       │   └── priceService.js
│       ├── routing              // Setup the routes, point them to controllers
│       │   └── angularRoutes.js
│       └── shopping             // Handles everything in the 'shopping' state
│           ├── cartDirective.js
│           └── shoppingController.js

// Below here is SERVER SIDE STUFF
├── controllers
├── models
└── views

Assets Structure

Questions?

Controllers, $scope,

By Tyler Bettilyon

Controllers, $scope,

  • 1,235