Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - reusing controller with different service on same page

Tags:

angularjs

in AngularJS I can define a controller for a section on the page. I can have a single page with multi-controllers.

<div ng-controller="ThisSectionController">
    .... 

</div>
<div ng-controller="ThatSectionController">
    ....
</div>

I can reuse a controller while sending a different configuration with ng-init

<div ng-controller="MyController" ng-init="i = 1">  
    {{ i }}
</div>
<div ng-controller="MyController" ng-init="i =2" >
    {{ i }}
</div>

This will output 1 and 2 as you expect it.

My question is - How can I reuse a controller and configure it to use a different service?

like image 579
guy mograbi Avatar asked May 30 '13 07:05

guy mograbi


1 Answers

Create a directive that injects $controller and use it in the linking function to instanciate the controller you want on a map of its instanciation arguments :

$controller("MyController", { $scope: scope, myService: myService})

scope is the scope variable of the linking function and myService is the service you can retrieve with the $injector service.

like image 188
lib3d Avatar answered Sep 16 '22 18:09

lib3d