AngularJS - reusing a controller with different services on one page

in AngularJS I can define a controller for a section on a page. I can have one page with multiple controllers.

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

I can reuse the controller when sending another configuration using 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.

My question is: how can I reuse the controller and configure it to use another service?

+6
source share
1 answer

Create a directive that introduces $controller and uses it in the bind function to initialize the controller you want on the map of its instanciation arguments:

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

scope is the scope variable of the binding function, and myService is a service that you can get with the $injector service.

+2
source

Source: https://habr.com/ru/post/946150/


All Articles