Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing inheritance in AngularJS directives

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?

like image 745
Andres Rovira Avatar asked Oct 04 '13 00:10

Andres Rovira


1 Answers

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>
like image 147
Denison Luz Avatar answered Oct 19 '22 05:10

Denison Luz