在 AngularJS 指令中实现继承

Implementing inheritance in AngularJS directives

本文关键字:实现 继承 指令 AngularJS      更新时间:2023-09-26

我正在尝试在AngularJS指令中实现OOP继承以制作可重用的控件。 我正在使用 Base2 的类定义进行继承。 我当时想的是实施这样的指令

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

然后我会为通用功能创建一个 BaseControl

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

然后我会创建特定的控件

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

问题是我想使用单个指令control-input并在属性中指定类型,但问题是当我创建指令时,我不知道如何检索类型

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

有什么想法吗?

您可以使用 link 函数的attrs参数来获取每个指令的类型。查看下面的代码并检查您的控制台。 (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>