【问题标题】:Inject service in all controllers在所有控制器中注入服务
【发布时间】:2015-08-28 08:32:12
【问题描述】:

我想使用https://github.com/alexcrack/angular-ui-notification 进行通知。我所有的控制器都需要它们。是否可以在我的所有控制器中注入“通知”(或“$log”或其他)?

【问题讨论】:

  • 您只需在控制器中加载Notification 服务作为依赖项。

标签: angularjs dependency-injection


【解决方案1】:

我认为你可以通过让你的控制器从一个通用的基本控制器继承。这样的事情可能会起作用:

angular.module('extending', [])

.controller('baseController', function(someService) {
   this.someService = someService;
})

.controller('extendedController', function($scope, $controller) {
  angular.extend(this, $controller('baseController', { $scope: $scope }));

   this.alert = this.someService.alert;
})

.service('someService', function() {
  this.alert = function() {
    window.alert('alert some service');
  };
});

HTML

  <body>
    <div ng-controller="extendedController as ex">
        <button ng-click="ex.alert()">Alert</button>
    </div>
  </body>

plunker 上的示例。 Related 在 SO 上发帖。 AngularjS extend doc.

【讨论】:

  • 非常感谢!你的回答很有帮助
  • 哇,不知道extend 功能,+1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 2016-01-28
  • 1970-01-01
相关资源
最近更新 更多