首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angularjs -将依赖注入多个控制器

Angularjs -将依赖注入多个控制器
EN

Stack Overflow用户
提问于 2014-12-03 20:57:46
回答 1查看 1.3K关注 0票数 2

我仍然是angular的新手,并且一直在构建一个简单的CRM应用程序。对于单个资源(restful API资源),我在angular应用程序中定义了3-4个路由和控制器。现在,有一组服务和模块我必须反复注入到每个控制器中。我知道每个控制器都有自己的作用域实例和工厂/服务的共享实例,但是有没有办法集中定义多个控制器的依赖关系呢?

在下面的示例中,$modalgrowlconfiguration$scope被注入到所有3个控制器中,我只想定义一次。

列表控制器

代码语言:javascript
复制
myApp.controller('VenueListCtrl', ['$scope', '$http', 'configuration', '$modal', 'growl',
  function ($scope, $http, configuration, $modal, growl) {
  }
]);

创建/新建控制器

代码语言:javascript
复制
myApp.controller('VenueCreateCtrl', ['$scope', '$http', '$location', 'configuration',
  function ($scope, $http, $location, configuration) {
  }
]);

详细信息控制器

代码语言:javascript
复制
myApp.controller('VenueDetailCtrl', ['$scope', '$routeParams', '$http', '$modal', 'configuration',
  function ($scope, $routeParams, $http, $modal, configuration) {
  }
]);
EN

回答 1

Stack Overflow用户

发布于 2014-12-03 21:17:56

你能做的最好的事情是:使用控制器的not-anonimus函数声明:

代码语言:javascript
复制
var depsToInject = ['$scope', 'growl', 'configuration', '$modal'];

myApp.controller('Ctrl1' , Ctrl1);

Ctrl1.$inject = depsToInject ;

function Ctrl1($scope, growl, configuration, $modal) {
    ....
}

myApp.controller('Ctrl2' , Ctrl2);

Ctrl2.$inject = depsToInject ;

function Ctrl1($scope, growl, configuration, $modal) {
    ....
}

等等。但这并不能完全统一声明,我认为没有更好的方法。但是,您可以尝试从另一方面并将您的依赖项包装为另一个依赖项,但我也不喜欢这种方式。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27272358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档