简体   繁体   中英

How to inject service into directive in AngularJS with ES6

Here are my directives index:

'use strict';

import SignupService from './core/services/signup.service';

import FooterDirective from './components/footer/footer.directive';
import MenuDirective from './components/menu/menu.directive';

export default angular.module('index.components', [])
    .directive('footer', FooterDirective)
    .directive('menu', [MenuDirective, function(SignupService) {}]);

and directive:

import tmpl from './menu.tpl.html';

class Menu {
    constructor($scope) {
        this.scope = $scope;
        this.restrict = 'AC';
        this.transclude = true;
        this.replace = true;
        this.templateUrl = tmpl;
        this.scope = {
            ngSrc: "@",
        };
    }

    link(scope, elem, attrs) {

        console.log(scope.SignupService);

        scope.logoutCall = () => {
            this.SignupService.logoutSubmit();
        }
    }
}
function factory() {
    "ngInject";

    return new Menu(...arguments);
}

export default factory;

I need to get access to Signup Service from Menu directive, but i have this error - Incorrect injection token! Expected service name as string, got function factory() Incorrect injection token! Expected service name as string, got function factory() . How and what is the best practice to inject service to directive. Thx for gelp.

Your dependency injection seems to be wrong.

Instead of

.directive('menu', [MenuDirective, function(SignupService) {}]);

there should be

.directive('menu', ['SignupService', function(SignupService) {}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM