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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With