Skip to content

Instantly share code, notes, and snippets.

@underhilllabs
Last active January 12, 2017 11:39
Show Gist options
  • Select an option

  • Save underhilllabs/5850168 to your computer and use it in GitHub Desktop.

Select an option

Save underhilllabs/5850168 to your computer and use it in GitHub Desktop.
notes on angularJS

controllers

Controller Responsibilities

  • responsible for setting up initial state of scope object
  • responsible for adding behavior to that scope object

Attaching the controller

<div id=masterWrapper ng-controller="MainCtrl">

Instantiate the Controller

myModule.controller('MainCtrl', function($scope, counterModel, counterHelper) {
...
});

Build the Controller

myModule.controller('MainCtrl', function($scope, counterModel, counterHelper) {
  $scope.counters = counterModel.getCounters();
  
  $scope.createCounter = function() {
    $scope.counters.push({
            title:'Green Hat',
            description:'Description pending',
            count:0,
            direction:1,
            status:'in-progress',
            step:2});
  };

});

Controller Best Practices

  • Controllers should be fine grained units of business logic that are easy to test.

Should be small and focused on the business logic of the view it is responsible for.

  • if writing code that is of interest to more than one place: good candidate for a service.

Only contain business logic

  • important that they never manipulate the DOM.
  • controller manipulates model => model binds to view => view updates automatically.
  • View is representative, not reactive of state of application.
  • view represents state of the ViewModel.

Controllers easy to test

  • controllers loosely coupled to rest of application and therefore do not talk directly to other controllers.
  • this makes it easy to write small. specific tests.

$scope object

  • responsible for storing application models
  • provides a context for expressions that operate on those models

Three main characteristics of $scope

  • detects changes with $watch
  • ability to propagate changes with $apply
  • $digest maybe?

View

  • HTML after is has been through the angular compilation cycle.

Templates

  • explicit
{{counter.title}}
  • implicit
<ul ng-repeat="counter in counters">

Filters

<ul ng-repeat="counter in counters| filter: {status:'in-progress'}">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment