AngularJS reusing the same controller on one page, with 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" gets an identifying property set, like "player = one" while the other gets "player = two").I'm not sure of the best way of pulling this off exactly

Here's a generic example of what I'm trying to accomplish:

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

<div ng-include src="'joystick/joy.tpl.html'" 

Should I:

Use a 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 might 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>


.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... not do this?

I realize this is similar to another, seemingly inconclusive stack post:

Problem courtesy of: methai



Since ngController is initialized before ngInit, in order to have data available in controller at once, you should wrap ngController in parent element with ngInit:

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

Original answer

I think simple ng-init would suffice:

<div ng-controller="JoystickCtrl" ng-init="player='one'">...</div>
<div ng-controller="JoystickCtrl" ng-init="player='two'">...</div>
Solution courtesy of: package


Store your config values in a data attribute, and retrieve it within the controller using $attrs. (The AngularJS ngInit documentation recommends to say clear of ng-init unless aliasing special properties of ngRepeat. ) A similar answer is here. This code snippet gives you the general idea:


<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>


function joystickCtrl($scope, $attrs) {
        $ = $;


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

Here is the full code in Plunker.

Discussion courtesy of: James Lawruk

This recipe can be found in it's original form on Stack Over Flow.