简体   繁体   English

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

[英]How do I initialize a nested controller in AngularJS?

Lets say we have an AngularJS view whith a master detail relation. 假设我们有一个AngularJS视图,其中有一个主要的细节关系。 eg order and order details. 例如订单和订单详细信息。

And we assume the details are rendered using an ng-repeat over order.details . 我们假设使用order.details ng-repeat details上的ng-repeat渲染细节。 eg 例如

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

I know that I can fetch the $scope.detail when the detailController is initialized. 我知道,我可以取$scope.detaildetailController被初始化。

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

But, that feels like a hack since I need to know in the controller what the ng-repeat variable name is, in this case detail 但是,这感觉像是黑客,因为我需要在控制器中知道ng-repeat变量名是什么,在这种情况下为detail

Is there any other way to get the active item from the repeater in the controller init? 还有其他方法可以从控制器init中的中继器获取活动项目吗?

If someone would change the ng-repeat variable name from detail to something else, then the controller would no longer work as expected. 如果有人将ng-repeat变量名称从detail更改为其他名称,则控制器将无法再按预期工作。

As I understood, you want to pass detail variable into nested scope, and you don't want to worry to remember variable name in case that you have to use nested Controller inside another ng-repeat? 据我了解,您想将detail变量传递给嵌套范围,并且您不想担心记住变量名,以防万一必须在另一个ng-repeat中使用嵌套Controller?

You can do it very easily 你可以很容易做到

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

and remember to use myVarname in detailController. 并记得在detailController中使用myVarname。 Of course that is not perfect, because you have to remember that detailController needs myVarname to work. 当然这不是完美的,因为您必须记住detailController需要myVarname才能工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM