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

标签 angularjs inheritance components directive

我一直在研究 AngularJS 并且研究了很多。我正在使用 AngularJS 指令构建可重用的自定义组件/小部件。我在这方面相当成功。但是,我想在做同样的事情时坚持继承。
让我用一个例子来解释。

我创建了一个指令 myButton创建一个具有所有样式和功能的按钮。现在我想扩展/继承这个 myButton创建 myToggleButton增加了一些特性和功能。我不想重写myButton又是特色。

我探索了各种选择。

  • 正如 https://gist.github.com/BrainCrumbz/5832057 中的建议,我创建了一个工厂/服务并将其注入(inject)到指令中。但这并不能让我充分利用遗产。我仍然需要重写大部分属性。
  • 我尝试使用普通的面向对象的 JavaScript 进行继承,但在这种情况下,我不会使用 AngulrJS 指令。我想严格遵循 Angular 的概念。

  • 因此,任何建议都将受到欢迎。

    最佳答案

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

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

    var BaseService = function() {};
    BaseService.prototype.toast = "french";
    BaseService.prototype.halloween = "scary";
    

    接下来让我们创建一个可以扩展的抽象服​​务(指令的逻辑相同)。
    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;
    }
    

    现在让我们创建一个实际的实现:
    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;
    }]);
    

    供服务使用
    module.factory
    

    代替
    module.directive
    

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

    然后
    French Toast
    Halloween is fun
    

    可以遵循类似的模式来允许 Controller 的完全继承,但还有更多的工作要做。

    关于angularjs - 继承 AngularJS 指令以创建可重用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18887626/

    相关文章:

    javascript - Angularjs 在同一个文本框上进行多次验证

    javascript - 单击时强制打开下拉菜单

    具有多父多态层次结构的 C++ VTable 实现

    c++ - move 赋值运算符和虚拟继承

    c++ - 从模板继承 : scope error?

    vue.js - Vue 警告 : 'Unknown custom element' with re-exported component

    javascript - Angular 隔离范围值可以由 "true"或空设置

    angularjs - Angular facebook-comments 指令

    java - 如何对自定义 Wicket 组件进行单元测试

    winforms - 就像Form类一样为Winforms Control添加Load事件