Roman Koliada
Roman Koliada

Reputation: 5082

Inject service in all controllers

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?

Upvotes: 1

Views: 864

Answers (1)

skubski
skubski

Reputation: 1606

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>

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

Upvotes: 5

Related Questions