如何将依赖项注入命名的角度指令控制器?

时间:2015-06-22 17:02:01

标签: javascript angularjs dependency-injection bundling-and-minification

如果我的代码类似于this question on injecting another controller to a directive

angular.module('paramApp', []);

angular.module('paramApp').controller('ParamCtrl', ['$scope', '$http', function($scope, $http) {
   .
   .
   .
}]);

angular.module('deviceApp', ['paramApp']);
angular.module('deviceApp').directive('DeviceDirective', function () {    
    return { 
    .
    .
    .
    controller: 'ParamCtrl' 
    };
});

当我缩小js时,$scope$http注入的依赖关系中断,如何在创建ParamCtrl时明确定义DeviceDirective的依赖关系以防止{{3} }}?

1 个答案:

答案 0 :(得分:1)

我对这个问题很迟,但我会试一试。 语法基于John Papa's Angular style guide

首先,您需要一种方法来使控制器可重用。将它从匿名函数转换为命名函数,并将其传递给角度应用程序,如下所示:

// Named controller function
ParamCtrl function($scope, $http) {
   this.doStuff
}

// Bind it to your app
angular.module('paramApp').controller('ParamCtrl', ['$scope', '$http', ParamCtrl );

// While we are at it, do the same with your directive
DeviceDirective function (controlerParam) {    
    return { 
        ...
        controller: controlerParam
    } 
}

// Bind it to your app
angular.module('deviceApp', ['ParamCtrl', DeviceDirective]);

但是,如果您打算将控制器的范围传递给您的指令,请参阅fiznool's post