AngularJS在一个页面上重用相同的控制器,具有不同的配置

时间:2013-06-04 20:53:46

标签: javascript angularjs angularjs-directive

我想在由同一控制器的不同实例控制的页面上显示两个元素,但是我需要注册一些独特的外部信息(一个“操纵杆“得到一个识别属性集,比如”player = one“,而另一个得到”player = 2“。)我不确定最好的方法是将其拉出来

这是我想要完成的一个通用示例:

<!-- 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?(fyi - 这可能是一个不正确的实现)

<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"});
});

或者......不这样做?

我意识到这与另一个看起来没有结果的堆栈帖子相似:

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:3)

将您的配置值存储在数据属性中,并使用$attrs.在控制器中检索它(AngularJS ngInit documentation建议清除ng-init,除非别名ngRepeat的特殊属性。)类似的答案是here。此代码段为您提供了一般概念:

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

<强>控制器:

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

查看:

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

<强> Here is the full code in Plunker