在所有控制器中注入服务 [英] Inject service in all controllers

查看:70
本文介绍了在所有控制器中注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use https://github.com/alexcrack/angular-ui-notification for notifications. I need them in all my controllers. Is it possible to inject 'Notification'(or '$log' or whatever) in all my controllers?

推荐答案

我认为您可以通过让控制器从通用basecontroller继承来实现.这样的事情可能会起作用:

I think you could by letting your controllers inherit from a common basecontroller. Something like this might work:

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 上的示例.关于SO的相关帖子. AngularjS 扩展文档.

Example on plunker. Related post on SO. AngularjS extend doc.

这篇关于在所有控制器中注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆