在所有控制器中注入服务

Rom*_*ada 1 dependency-injection angularjs

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

sku*_*ski 5

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

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');
  };
});
Run Code Online (Sandbox Code Playgroud)

超文本标记语言

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

plunker上的例子。SO 上的相关帖子。AngularjS扩展文档。