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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With