问题描述:

Lets say we have an AngularJS view whith a master detail relation.

e.g. order and order details.

And we assume the details are rendered using an ng-repeat over order.details.

e.g.

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

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

Is there any other way to get the active item from the repeater in the controller init?

If someone would change the ng-repeat variable name from detail to something else, then the controller would no longer work as expected.

网友答案:

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?

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. Of course that is not perfect, because you have to remember that detailController needs myVarname to work.

相关阅读:
Top