Skip to content

Instantly share code, notes, and snippets.

@colemanw
Last active July 19, 2021 17:15
Show Gist options
  • Save colemanw/a3814f4bb77d1039316512a224fd3444 to your computer and use it in GitHub Desktop.
Save colemanw/a3814f4bb77d1039316512a224fd3444 to your computer and use it in GitHub Desktop.
Traits for AngularJS controllers
angular.module('cowModule').factory('cowTrait', function() {
// Private function (not available to controller using this trait)
function getSound() {
return 'Moo';
}
// Public properties & methods for use as a trait
return {
cows: 0,
addCow: function() {
this.cows++;
}
// Methods have full access to controller object as `this` (including bindings like `color`)
getHorseSounds: function() {
return this.cows + ' cows say ' + getSound() + ' in the ' + this.color + ' barn.';
}
};
});
angular.module('farmModule', ['cowModule', 'horseModule']); // require modules whose traits we want to use
angular.module('farmModule').component('barn', {
bindings: {color: '<'},
// Declare controller and import traits (via service injection)
controller: function($scope, cowTrait, horseTrait) {
// This adds all properties of cowTrait & horseTrait to the controller object
// (ctrl === this, it's just a local reference; handy for use within functions with a different `this` binding)
var ctrl = angular.extend(this, cowTrait, horseTrait);
// Private function is not available to the traits
function countAnimals() {
return ctrl.cows + ctrl.horses;
}
this.$onInit = function() {
this.addCow();
this.addHorse();
alert(countAnimals() + ' animals in the ' + ctrl.color + ' barn.');
}
}
});
angular.module('horseModule').factory('horseTrait', function() {
// Private function (not available to controller using this trait)
function getSound() {
return 'Neigh';
}
// Public properties & methods for use as a trait
return {
horses: 0,
addHorse: function() {
this.horses++;
}
// Methods have full access to controller object as `this` (including bindings like `color`)
getHorseSounds: function() {
return this.horses + ' horses say ' + getSound() + ' in the ' + this.color + ' barn.';
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment