【问题标题】:Implementing inheritance in AngularJS directives在 AngularJS 指令中实现继承
【发布时间】:2013-10-10 20:37:01
【问题描述】:

我正在尝试在 AngularJS 指令中实现 OOP 继承,以制作可重用的控件。我使用Base2's Class definition 进行继承。我的想法是实现这样的指令

<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(); */
});

有什么想法吗?

【问题讨论】:

    标签: javascript oop angularjs inheritance angularjs-directive


    【解决方案1】:

    您可以使用链接函数的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>
    

    【讨论】:

    • 是的,问题是我想将 DDO 本身作为继承返回,将 return {...} 替换为 return new TextControl(...) 或类似的东西,到那时我没有关于属性或范围的信息.
    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多