4

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?

szpic
  • 4,346
  • 15
  • 54
  • 85

2 Answers2

1

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.

kiswa
  • 14,737
  • 1
  • 21
  • 29
  • Unfortunately there is a requirement that that need to be two directives. – szpic Jul 07 '15 at 12:32
  • That's a very specific and odd requirement. Is this some kind of homework? – kiswa Jul 07 '15 at 12:33
  • No I'm already after school years :) At this moment this is working as one directive and depending on the parameter but it was rejected as a error prone. – szpic Jul 07 '15 at 12:37
  • Interesting. I assume the errors it's prone to are human (not updating the attribute?). I guess if you have to work within those requirements your hands are somewhat tied. – kiswa Jul 07 '15 at 12:39
0

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.

Community
  • 1
  • 1
OfirYaron
  • 157
  • 1
  • 9