6

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?

1
  • 1
    + 1 - Did not know about ng-init Commented May 30, 2013 at 7:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Let me see if I got it right - I pass a string on the directive to specify the service name, and then I use some $injector API something like $injector.getService(serviceName)? So my directive will look something like this: <my-dir controller-name="MyController" service-name="MyService"> ... </my-dir> and this should replace the previous <div ng-controller="MyController"> right?
Actually - now that I think about it - why not use $injector in the Controller and then pass service name in ng-init?
You are right, it's a quite better approach ! Actually I presented the controller unit test approach to mock a service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.