Angular controller in directive cause strict di error

吃可爱长大的小学妹 提交于 2019-12-13 05:19:18

问题


I use the ng-strict-di mod in my app. It works for all my DI, except when I try to use a controller in a directive. FYI I use the John Papa style guide to format my code.

Here is my directive :

(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();
            }
        }
    }
})();

So I inject explicitly my ServiceSvc in my MyDirectiveCtrl but in my Chrom console I've got an error about strict 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)

Any idea why i get this error ?


回答1:


I think you have to use the controller defined in your directive outside, as below

 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();
        }
    }


来源:https://stackoverflow.com/questions/33256367/angular-controller-in-directive-cause-strict-di-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!