我如何使用数组语法与指令控制器的依赖注入



我希望能够使用内联函数指定指令的控制器,但我也希望使用ng-strict-di。这样做需要什么语法?

(function(){
    angular.module("myAngularModule")
    .directive("myDirective", function(){
        return {
            restrict: 'E',
            templateUrl: "templates/my-template.html",
            link: function ($scope, element, attrs) {
                // ...
            },
            // This causes an ng-strict-di exception because I'm using implicit annotation for the dependencies - what is the correct syntax?
            controller: function($scope, myService) { 
                // ...
            }
        };
    })
    // This syntax is fine
    .controller("myWorkingController",["$scope","myService", function($scope, myService){ 
        // ...
    }]);
});

仅仅因为控制器是匿名的并不意味着语法会改变。像传递任何其他控制器分配一样传递数组。Angular会理解的。

controller: ["$scope","myService", function($scope, myService){
    // ...
}]

将服务注入到您的directive as中,就像注入到控制器中一样,

.directive("myDirective", function(myService){

并将其从控制器中移除。

.directive("myDirective", function(myService){
    return {
        restrict: 'E',
        templateUrl: "templates/my-template.html",
        link: function ($scope, element, attrs) {
            // ...
        },
        controller: function($scope) { 
            // ...
        }
    };
})

directivecontroller中可以访问myService

最新更新