AngularJS reuses the same controller on the same page with a different configuration

I want to display two elements on a page controlled by different instances of the same controller , but I need to register some external information that will be unique (one "joystick" receives a set of identification properties as "player = one", while the other gets "player = two"). I'm not sure of the best way to get it for sure

Here is a general example of what I'm trying to accomplish:

<!-- These need to have different configurations --> <div ng-include src="'joystick/joy.tpl.html'" ng-controller="JoystickCtrl">...</div> <div ng-include src="'joystick/joy.tpl.html'" ng-controller="JoystickCtrl">...</div> 

Should I:

Use directive?

 <div ng-include src="'joystick/joy.tpl.html'" ng-controller="JoystickCtrl" player="one">...</div> <div ng-include src="'joystick/joy.tpl.html'" ng-controller="JoystickCtrl" player="two">...</div> 

Use $ injector? (fyi - this may be an incorrect implementation)

 <div ng-controller="DualJoyCtrl"> <div ng-include src="'joystick/joy.tpl.html'" ng-controller="joyOne" player="one">...</div> <div ng-include src="'joystick/joy.tpl.html'" ng-controller="joyTwo" player="two">...</div> </div> ----- .controller('DualJoyCtrl', function ($injector, JoystickCtrl, $scope, $rootScope) { $scope.joyOne = $injector.instantiate(JoystickCtrl, {$scope: $rootScope.$new(), player:"one"}); $scope.joyTwo = $injector.instantiate(JoystickCtrl, {$scope: $rootScope.$new(), player:"two"}); }); 

Or ... don't do it?

I understand that this seems like another seemingly flimsy message on the stack:

+6
source share
2 answers

Edit

Since ngController is initialized to ngInit in order to have access to the data in the controller at the same time, you must wrap ngController in the parent element using ngInit:

 <div ng-init="player = 'one'"> <div ng-controller="JoystickCtrl"> ... </div> </div> 

Original answer

I think a simple ng-init will suffice:

 <div ng-controller="JoystickCtrl" ng-init="player='one'">...</div> <div ng-controller="JoystickCtrl" ng-init="player='two'">...</div> 
+7
source

Store the configuration values ​​in the data attribute and retrieve them in the controller using $attrs. ( The AngularJS documentation ngInit recommends saying clear of ng-init if the special properties of ngRepeat are not imposed.) A similar answer is here . This piece of code gives you a general idea:

Index.html:

 <div ng-include ng-controller="JoystickCtrl" src="'same.html'" data-id="1"></div> <div ng-include ng-controller="JoystickCtrl" src="'same.html'" data-id="2"></div> 

Controller:

 function joystickCtrl($scope, $attrs) { $scope.id = $attrs.id; }; 

View:

 <h2>Joystick: {{id}}</h2> 

Here is the full code in Plunker .

+3
source

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


All Articles