Last active
July 19, 2021 17:15
-
-
Save colemanw/a3814f4bb77d1039316512a224fd3444 to your computer and use it in GitHub Desktop.
Traits for AngularJS controllers
This file contains 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
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.'; | |
} | |
}; | |
}); |
This file contains 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
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.'); | |
} | |
} | |
}); |
This file contains 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
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