Skip to content

Instantly share code, notes, and snippets.

@vojtajina
Created December 13, 2011 04:50
Show Gist options
  • Save vojtajina/1470651 to your computer and use it in GitHub Desktop.
Save vojtajina/1470651 to your computer and use it in GitHub Desktop.
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();
@ThomasBurleson
Copy link

Feeling stupid, but how does line 31 work?
$scope is a closure variable not a property of this.
So this.$scope === undefined (I think).

@vojtajina
Copy link
Author

You don't have to feel stupid... I'm assuming that you assigned scope to this:

this.$scope = $scope;

It should have been there explicitly, so I updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment