【问题标题】:How to inject dependencies to a named angular directive controller?如何将依赖项注入命名的角度指令控制器?
【发布时间】:2015-06-22 17:02:00
【问题描述】:

如果我有类似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的注入依赖中断,如何在创建DeviceDirective时显式定义ParamCtrl的依赖以防止uncaught injector issues with bundled js

【问题讨论】:

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


    【解决方案1】:

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

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

    // 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

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2021-09-08
      • 2013-10-29
      • 2016-08-04
      相关资源
      最近更新 更多