Shift N' Tab Shift N' Tab - 22 days ago 5
Javascript Question

How to inject a controller to a service?

Normally the service is injected in a controller.

controller.js

angular
.module('myApp')
.factory('myService', function($http){

var myService = {
get: get
};

return myService;

function get(){
// Get function.
}

});


service.js

angular
.module('myApp')
.controller('myController', function(myService) {

myService.get();

});


But it is possible to reverse the way? To Inject a controller to a service?

Answer

The straight answer would be No. You don't inject a controller to a service or anywhere else for that matter. The real question is why would you want to do that?

// Update

Assuming you are referring to https://material.angularjs.org/latest/api/service/$mdDialog. The mdDialog service expects a controller function, you could probably pass it a reference to a function.

Example:

angular.module('app',[])
  .factory('myService', function(){
    return {
      myMdDialogCtrl: function($scope, $mdDialog, items){
        // Controller for MD Dialog
      }
    }
  })
  .controller('ctrl1', function($scope, $mdDialog, myService){
    $mdDialog.show({
      ...
      controller: myService.myMdDialogCtrl
    })
  })
  .controller('ctrl2', function($scope, $mdDialog, myService){
    $mdDialog.show({
      ...
      controller: myService.myMdDialogCtrl
    })
  })