Reputation: 4496
Assume that I have a directive:
.directive('money', ['Service', function (Service) {
/*
* Some code
*/
controller: ['$scope', '$element', '$attrs', '$parse', function (scope, cElement, attrs, $parse) {
scope.someValue=1;
scope.someFunction = function(){
console.writeline('money');
}
}
and there is a second directive:
.directive('cash', ['Service', function (Service) {
/*
* Some code
*/
controller: ['$scope', '$element', '$attrs', '$parse', function (scope, cElement, attrs, $parse) {
scope.someValue=1;
scope.someFunction = function(){
console.writeline('cash');
}
}
As you can see only difference between those two directives is content of a one function.
So perfect way would be inherit all the controller and shadow that someFunction
Is it even possible in angular to make something like this or I should leave two directives with so small diferences?
Upvotes: 4
Views: 1093
Reputation: 14987
Why not just have a console
directive that grabs what to write from an attribute on the directive's element?
So, instead of a <div data-money></div>
and <div data-cash></div>
You'd have <div data-console text="money"></div>
and <div data-console text="cash"></div>
.
Basically, pull what's different into attributes that can be brought into a more generic directive.
Based upon comments, how about this? Create the controller as a standalone function, then use that same controller in both directives.
At this point though, I'm not sure it's going to save you much (or any) code and may be overkill for this refactoring. Considering the minor differences, it may make more sense to just keep it the way you have it.
Upvotes: 1
Reputation: 157
Yes, there are options for inheritance, It was discussed here before: AngularJS controller inheritance
Edit: in addition you can take the common functionality and share it through an injected service, the variations may be passed as a parameter.
Upvotes: 0