Extending base directive functionality to other di

2019-09-11 07:59发布

问题:

I just wanted to check is this functionality is possible in angularjs.

Eg: I have base directive with some common functions but in my whole application all the directives need this functions to be implemented so more code duplication occurs, I am expecting same functionality as extends(inheritance) in Java.

Is it possible to achieve this functionality in angularjs.?

As per my requirement i can't archive this function by moving this code to services or factory because it is like all of by directives in the application need to perform this operation on linking, so now all of my directive link function container same functionality with duplicate code.

I am expecting something like extending base directive functionality for all my directives.

[Note] Most of the directives in my application has isolated scope.

回答1:

The answer primarily lies in JS domain, and finding patterns for reusable code is a good challenge. Angular got extend, copy and merge, but that's all, modules and DI are just ways to get around the limitations of ES5.

Here's a hint on how you can create mixins from directive definition objects.

app.directive('blockBase', function () {
    return {
        link: function (scope, element, attrs) {
            scope.title = 'block';
        }
    };
});

app.directive('brickBase', function () {
    return {
        restrict: 'E',
        scope: true,
        link: function (scope, element, attrs) {
            // ...
        }
    };
});

app.directive('block', function (blockBaseDirective, brickBaseDirective) {
    var blockDirective = angular.extend(brickBaseDirective[0], {
        name: 'brick',
        restrict: 'EA',
        scope: {
            title: '='
        }
    });

    blockDirective.compile = function (element, attrs) {
        // ...
        return {
            post: function (scope, element, attrs) {
                blockBaseDirective[0].link(scope, element, attrs);
                scope.title += ' offspring';
            }
        };
    };

    return blockDirective;
});

You should decide for yourself if this approach looks better than decorators.

Using named functions outside of controller/directive definitions is popular way to get rid of duplicate code, not an elegant one. And of course you can share functions or classes among directives with custom DDO properties. However, factories are still more suitable for that.