Forked from vojtajina/angular-ctrl-export-proposal.js
Created
February 7, 2012 15:56
-
-
Save ThomasBurleson/1760379 to your computer and use it in GitHub Desktop.
Angular: Export Ctrl Methods Proposal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment