我想在由相同 Controller 的不同实例控制的页面上显示两个元素,但是我需要注册一些唯一的外部信息(一个“游戏杆”获得了一个标识属性集,例如“player = one”,而另一个获得“玩家=两个”)。我不确定将其准确地提取的最佳方法
这是我要完成的一般示例:
<!-- 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>
我是不是该:
使用指令?
<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>
使用$ injector? (仅供引用-这可能是错误的实现)
<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"});
});
还是...不这样做?
我意识到这类似于另一个看似不确定的堆栈文章:
最佳答案
编辑
由于ngController是在ngInit之前初始化的,因此为了立即在 Controller 中获得数据,您应该使用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>