JSFiddle - React, Tailwind, and code Playground
by jrab227
HTML
<div ng-app="myModule">
<div ng-controller="cleanController">
<a-Reusable-Template
data="firstData"
behavior="boundBehavior"></a-Reusable-Template>
<a-Reusable-Template
data="secondData"
behavior="boundBehavior"></a-Reusable-Template>
</div>
</div>
JavaScript
angular.module('myModule', [])
.service('reqData1', [function(){
//A fully decoupled model
return ["string1", "AHHH", "string3"]
}])
.service('reqData2', [function(){
//A different model if you will
return ["string1", "Quiet", "string3"]
}])
.service('reqBehavior', [function(){
//Decoupled into the module the behavior. Now I can modify
//ALL behaviors here. When requirements change for example.
return function(coolInfo) {
alert(coolInfo);
};
}])
.directive('aReusableTemplate', [ function(){
return {
scope: {
data: '=',
behavior: '&'
},
template: '<button ng-click="clickBehavior()">Click Me!</button>',
restrict: 'E',
link: function(scope, elems, attrs){
scope.clickBehavior = undefined;
//This is required for asyncronousness of data-injection if you're new
//to this. This binds the data to the on-click
scope.$watch('data', function(newval){
//This statement is also required for async data injection
if(newval){
scope.clickBehavior = function(){
scope.behavior()(newval[1])
}
}
});
return null
}
};
}])
.controller('cleanController',
['$scope', 'reqData1', 'reqData2', 'reqBehavior',
function($scope, reqData1, reqData2, reqBehavior){
//A true controller. No data creation. Fully testable.
$scope.firstData = reqData1;
$scope.secondData = reqData2;
$scope.boundBehavior = reqBehavior;
}]);