指令中的角度控制器导致严格的di错误

时间:2015-10-21 10:03:48

标签: javascript angularjs angularjs-directive

我在我的应用中使用ng-strict-di mod。它适用于我的所有DI,除非我尝试在指令中使用控制器。仅供参考我使用John Papa风格指南来格式化我的代码。

这是我的指示:

(function () {
    'use strict';

    angular
        .module('app.mymodule')
        .directive('myDirective', myDirective);

    myDirective.$inject = [];

    function  myDirective() {
        var directive = {
            bindToController: true,
            controller: MyDirectiveCtrl,
            controllerAs: 'vm',
            restrict: 'E',
            scope: {
                data:'='
            },   
            templateUrl: 'my-directive-template.html',  
        };
        return directive;

        MyDirectiveCtrl.$inject = ['ServiceSvc'];
        function MyDirectiveCtrl(ServiceSvc) {
            var vm = this;

            vm.foo = foo;

            function foo() {
                ServiceSvc.bar();
            }
        }
    }
})();

所以我在我的ServiceSvc明确注入我的MyDirectiveCtrl,但在我的Chrom控制台中,我遇到了严格的DI错误:

Error: [$injector:strictdi] MyDirectiveCtrl is not using explicit annotation and cannot be invoked in strict mode
http://errors.angularjs.org/1.4.3/$injector/strictdi?p0=MyDirectiveCtrl 
    at vendor.js:10
    at Function.annotate [as $$annotate] (vendor.js:209)
    at Object.invoke (vendor.js:233)
    at extend.instance (vendor.js:443)
    at nodeLinkFn (vendor.js:374)
    at vendor.js:397
    at processQueue (vendor.js:703)
    at vendor.js:704
    at Scope.$eval (vendor.js:748)
    at Scope.$digest (vendor.js:743)

我知道为什么会收到此错误?

1 个答案:

答案 0 :(得分:3)

我认为您必须使用外部指令中定义的控制器,如下所示

 angular
        .module('app.mymodule')
        .directive('myDirective', myDirective);

myDirective.$inject = [];

function  kissNotificationList() {
    var directive = {
        bindToController: true,
        controller: MyDirectiveCtrl,
        controllerAs: 'vm',
        restrict: 'E',
        scope: {
            data:'='
        },   
        templateUrl: 'my-directive-template.html',  
    };
    return directive;


}

//direcitves controller

 MyDirectiveCtrl.$inject = ['ServiceSvc'];

 function MyDirectiveCtrl(ServiceSvc) {
        var vm = this;

        vm.foo = foo;

        function foo() {
            ServiceSvc.bar();
        }
    }