6

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'" 
     ng-controller="JoystickCtrl">...</div>

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

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

4

2 回答 2

7

编辑

由于 ngController 是在 ngInit 之前初始化的,为了让控制器中的数据立即可用,您应该使用 ngInit 将 ngController 包装在父元素中:

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

原始答案

我认为简单的 ng-init 就足够了:

<div ng-controller="JoystickCtrl" ng-init="player='one'">...</div>
<div ng-controller="JoystickCtrl" ng-init="player='two'">...</div>
于 2013-06-04T20:57:27.153 回答
3

将您的配置值存储在数据属性中,并在控制器中使用$attrs.AngularJS ngInit 文档建议清除,ng-init除非别名化 ngRepeat 的特殊属性。)类似的答案是here。此代码片段为您提供了大致思路:

索引.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>

控制器:

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

看法:

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

这是 Plunker 中的完整代码

于 2014-12-08T19:02:54.010 回答