Using ES6 Classes as Angular 1.x directives

后端 未结 10 839
南旧
南旧 2020-12-04 07:57

I\'m doing a small project to play around the goody bag the ES6 is bringing, I\'m trying to set register a class as an angular directive, but I\'m running into this error \"

10条回答
  •  离开以前
    2020-12-04 08:24

    @Michael is right on the money:

    the module.directive() method expects a factory function

    However I solved it using another technique, a little cleaner I suppose, It works fine for me, it's not perfect though... I defined a static method that returns a the factory expected by module()

    class VineDirective {
        constructor($q) {
            this.restrict = 'AE';
            this.$q = $q;
        }
    
        link(scope, element, attributes) {
            console.log("directive link");
        }
    
        static directiveFactory($q){
            VineDirective.instance = new VineDirective($q);
            return VineDirective.instance;
        }
    }
    
    VineDirective.directiveFactory.$inject = ['$q'];
    
    export { VineDirective }
    

    And in my app I do:

    angular.module('vineyard',[]).directive('vineScroller', VineDirective.directiveFactory)
    

    I believe there's no other way to use classes + directives that going through hacks like this at this point, just pick the easy one ;-)

提交回复
热议问题