ThomasBurleson
2/7/2012 - 3:56 PM

Angular: Export Ctrl Methods Proposal

Angular: Export Ctrl Methods Proposal

// GOOGLE3 usage - bigger projects
var MyController = function($scope, $location) {

  // controller's private state
  this.$location = $location;
  this.some = 12;
  this.$scope = $scope;

  // methods accessible from template
  // these methods (defined in constructor) should contain only few logic,
  // should rather delegate to controller methods (defined on prototype)
  // it's a layer between scope and controller
  var ctrl = this;
  $scope.method = function(arg1, arg2) {
    // do some simple stuff..

    // or call method defined on prototype
    ctrl.performSomeMoreLogic(arg1);
    
    // or you can pass scope into method
    ctrl.anotherLogic($scope, arg2);
  };

  // publish properties to scope
  $scope.value = 0;

  // we can bind methods as well
  $scope.publicMethod = this.performSomeMoreLogic.bind(this);
}

MyController.prototype.performSomeMoreLogic = function(arg1) {
  this.$scope.value = 1 + 1;
};

MyController.prototype.anotherLogic = function(scope, arg1) {
  scope.value = 1 + 1;
};


// Simple toy apps usage
function FunnyController($scope, $location) {
  var somePrivate = function() {};
  var otherPrivate = 11;

  // just don't care about prototype, define all in constructor...
  $scope.method = function() {
    // access everything through closure...
    $scope.value = 1;
    otherPrivate = somePrivate();
  };

  $scope.value = 0;
}


// UNIT TESTING
var scope = $rootScope || {};
var ctrl = $injector.instantiate(MyNamespace.MyController, {$scope: scope});

// test from scope (public)
scope.method(1);
expect(scope.value).toBe(2);


// or controller directly, without scope
ctrl.anotherLogic({}, 1);
expect(ctrl).toBeWhatever();