9

I'm trying to implement OOP inheritance in AngularJS directives to make reusable controls. I'm using Base2's Class definition for inheritance. What I was thinking was to implement a directive like this

<control-input type="text" name="vendor_name"></control-input>

Then I would created a BaseControl class for common functionality

angular.module('base',[]).factory('BaseControl', function() {
  return Base.extend({
    'restrict': 'E',
    'require': '^parentForm'
    /* ... */
  };
});

And then I would create specific controls

angular.module('controls',['base']).factory('TextControl', function(BaseControl) {
  return BaseControl.extend({
    /* specific functions like templateUrl, compile, link, etc. */
  };
});

The issue is that I want to use a single directive control-input and specify the type in the attributes, but the problem is when I create the directive, I don't know how to retrieve the type

angular.module('controls',['controls']).directive('control-input', function(TextControl) {
   /* here it should go some code like if (type === 'text') return new TextControl(); */
});

Any ideas?

1 Answer 1

1

You could use the attrs params of the link function to get the type of each directive. Take a look at the code below and check your console. (http://jsbin.com/oZAHacA/2/)

<html ng-app="myApp">
  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
   <script>
      var myApp = angular.module('myApp', []);

     myApp.directive('controlInput', [function () {
        return {
          restrict: 'E',
          link: function (scope, iElement, iAttrs) {
              console.log(iAttrs.type);
          }
        };
     }]);

    </script>
  </head>
 <body>

    <control-input type="text" name="vendor_name"></control-input>

 </body>
</html>
1
  • Yes, the problem is that I want to return the DDO itself as an inheritance, replace the return {...} by return new TextControl(...) or something like that, by that time I have no information about attributes nor scope. Commented Oct 4, 2013 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.