【问题标题】:Inheriting Directives in Angular在 Angular 中继承指令
【发布时间】:2014-10-28 20:20:54
【问题描述】:

我试图让我的 Angular 项目尽可能地模块化。我目前有 3 个嵌套指令构成我的项目的基础。

最底层的指令将始终具有相同的核心功能和范围对象,但根据用例需要额外的范围对象和功能。该应用程序非常大,因此保持一切尽可能解耦很重要,并且遵循 DRY 原则。

在 python 风格的 OOP 中,我只需要继承所有的属性和函数,然后添加它们。 Angular中有类似的东西吗?

例如:

基地

myApp.directive('itemOption', function () {
    return {
        restrict: 'E',
        templateUrl: "item_option.html",
        scope: {
            'lowest': '=',
            'middle': '=',
            'high': '=',
            'ngModel': '=',
        },
        controller: function ($scope) {
            $scope.prop1 = "Default 1"
            $scope.prop2 = "Default 2"
        }
    }
}

一个重复的指令,将被用来代替基数

myApp.directive('itemOptionVariation1', function () {
    return {
        restrict: 'E',
        templateUrl: "item_option.html",
        scope: {
            'lowest': '=',
            'middle': '=',
            'high': '=',
            'ngModel': '=',
        },
        controller: function ($scope) {
            $scope.prop1 = "Default 1"
            $scope.prop2 = "Default 2"

            // Unique to this directive
            $scope.prop900 = "Penguins"
        }
    }
}

还有一个

myApp.directive('itemOptionVariation2', function () {
    return {
        restrict: 'E',
        templateUrl: "item_option.html",
        scope: {
            'lowest': '=',
            'middle': '=',
            'high': '=',
            'ngModel': '=',
        },
        controller: function ($scope) {
            $scope.prop1 = "Default 1"
            $scope.prop2 = "Default 2"

            // Unique to this directive
            $scope.prop3 = "This is awesome"
        }
    }
}

【问题讨论】:

    标签: javascript python angularjs


    【解决方案1】:

    您可以使用 require:[^parent_directive1, ^parent_directive2] 作为指令属性。请检查以下示例。

    myApp.directive('itemOptionVariation2', function () {
        return {
            restrict: 'E',
            templateUrl: "item_option.html",
            require: ['^itemOption', '^itemOptionVariation1'],
    

    这不完全是继承,而是组合。不过,这已经解决了我的需求。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 2011-02-19
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多