Angular - get controller instance in service

I have a problem, I am trying to get an instance of a controller in my service:

myAppModule.service('modalService',
function ($modal, $controller) {
   var controller = $controller('ExperienceDetailsModalCtrl');
});

      

but i have error: TypeError: Cannot read property '$ scope' from undefined

Is it possible to access the controller (defined in another file) and pass it to the modal?

My controller:

myAppIndexModule
.controller('ExperienceDetailsModalCtrl', function ($scope) {

});

      

+3


source to share


1 answer


You cannot access the controller scope in service

, factory

or provider

. The data you want to share must be placed inside the service. and make it available to another controller.

I think you want to pass the control scope to $modal

, then you can achieve this by executing the controller itself.

$modal.open({$scope: $controller('ExperienceDetailsModalCtrl', {$scope: $scope}), templateUrl: 'abc.html'})

      



Update

You can do it like below

myAppModule.service('modalService',
function ($modal, $controller, $rootScope) {
   var scope = $rootScope.$new(true);
   $controller('ExperienceDetailsModalCtrl',{scope: $scope });
   //in scope now you will have ExperienceDetailsModalCtrl scope
});

      

+4


source







All Articles