继承AngularJS指令以创建可重用的组件

swa*_*his 5 inheritance components directive angularjs

我已经在AngularJS工作了一段时间并且已经研究了很多.我正在使用AngularJS指令构建可重用的自定义组件/小部件.我在这方面非常成功.但是,我希望在做同样的事情时坚持继承.让我举个例子来解释一下.

我创建了一个指令myButton,创建一个包含所有样式和功能的按钮.现在我想扩展/继承它myButton以创建一个myToggleButton具有一些附加功能的功能.我不想myButton再次重写功能.

我已经探索了各种选择.

  1. 正如https://gist.github.com/BrainCrumbz/5832057中所建议的那样,我创建了一个工厂/服务并将其注入指令中.但这不允许我充分利用遗产.我仍然需要重写大部分属性.

  2. 我尝试使用普通的面向对象的JavaScript进行继承,但在这种情况下我不会使用AngulrJS指令.我想严格遵循Angular概念.

所以任何建议都会受到欢迎.

Enz*_*zey 4

我还发现大多数继承示例不太理想,但我提出了一个我认为干净且允许完全继承的解决方案。

由于服务和指令中没有可用的原型信息,并且直接扩展对象并不好,您将需要创建一个高级基类,其中可以包含常量或非常简单的通用逻辑。

var BaseService = function() {};
BaseService.prototype.toast = "french";
BaseService.prototype.halloween = "scary";
Run Code Online (Sandbox Code Playgroud)

接下来让我们创建一个可以扩展的抽象服​​务(与指令的逻辑相同)。

module.factory('AbstractDirective', function(
    $http, $q, $rootScope, $compile, $timeout) {
    $.extend(this, new BaseService);

    // Additional logic and methods should be appended onto 'this'
    this.doStuff = function() {
        alert("abstract function called");
    };

    this.halloween = 'fun';
    // If adding a variable to the prototype of this extended class is desired
    //     then this function would need to be extracted to its own variable
    //     where the prototype values can be set before the function
    //     is passed to the factory. 

    return this;
}
Run Code Online (Sandbox Code Playgroud)

现在让我们创建一个实际的实现:

module.directive('DirectiveImpl', ['AbstractDirective', function(AbstractDirective) {
    $.extend(this, AbstractDirective);
    // A great part about this implementation pattern is that
    //   DirectiveImpl does not need to pass anything to construct AbstractDirective.
    // Meaning changes to AbstractDirective will have less impacts
    //   on implementing classes.

    this.doStuff = function () {
        // Call
        AbstractDirective.doStuff();
        // Implement some logic additional
        alert(this.toast + "Toast\nHalloween is " + this.halloween );
    }

    return this;
}]);
Run Code Online (Sandbox Code Playgroud)

用于服务用途

module.factory
Run Code Online (Sandbox Code Playgroud)

代替

module.directive
Run Code Online (Sandbox Code Playgroud)

当 DirectiveImpl 调用 doStuff 函数时,您将收到 2 个警报:

abstract function called
Run Code Online (Sandbox Code Playgroud)

然后

French Toast
Halloween is fun
Run Code Online (Sandbox Code Playgroud)

可以遵循类似的模式来允许控制器的完全继承,但要使其发挥作用还需要更多的工作。