如何在 AngularJS 中初始化嵌套控制器?

How do I initialize a nested controller in AngularJS?

假设我们有一个 AngularJS 视图,其中包含主从关系。 例如订单和订单详情。

并且我们假设细节是使用 ng-repeat 而不是 order.details 呈现的。 例如

<div ng-repeat="detail in orderCtl.order.details" 
     ng-controller="detailController as detailCtl">

我知道我可以在 detailController 初始化时获取 $scope.detail

 /* initcontroller */ 
 function($scope) {
      console.log($scope.detail); //<-- this is the active item
 }

但是,这感觉像是一个 hack,因为我需要在控制器中知道 ng-repeat 变量名称是什么,在这种情况下 detail

有没有其他方法可以从控制器初始化中的中继器获取活动项目?

如果有人将 ng-repeat 变量名从 detail 更改为其他名称,那么控制器将不再按预期工作。

据我了解,您想将详细信息变量传递到嵌套范围中,并且您不想担心记住变量名称以防您必须在另一个 ng-repeat 中使用嵌套控制器?

你可以很容易做到

<div ng-repeat="detail in orderCtl.order.details" 
 ng-controller="detailController as detailCtl" ng-init="myVarname= detail">

<div ng-repeat="historydetails in orderCtl.historyorder.details" 
 ng-controller="detailController as detailCtl" ng-init="myVarname= historydetails ">

并记得在 detailController 中使用 myVarname。 当然这并不完美,因为您必须记住 detailController 需要 myVarname 才能工作。