How do I initialize a nested controller in AngularJS?

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.

Answers


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.


Need Your Help

Change the text of the label of the menu cells

ios menu swift

I downloaded as a sample file from Github ENSwiftSideMenu to take a cue for a possible menu in my app, the file MyMenuTableViewController.swift I wanted to change the strings that are found in the ...

Returning multiple values with INDEX array formula

excel indexing excel-formula match vlookup

I have made multiple attempts with this array formula but have had no luck so far. The solutions that are posted all seem similar but none have worked yet.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.