Using ng-init to send data from a ng-repeat to another controller

432 Views Asked by At

I have a html file that runs a ng-repeat and then each item in that ng-repeat will generate a template which also has it's own controller

On the html file I have something like:

<div ng-repeat="item in items">
  <div ng-include="'template.html" ng-init="getData(item)"></div>
</div>

And then this template has it's own controller.

The controller has the function getData(item) and looks something like this:

$scope.getData = function(item){
 var chapter = item;
}

$scope.myVec = chapter.myVec.length;

template.html looks like:

<div ng-controller = "Controller">

<p>{{myVec}}</p>

</div>

And then I get an error on the console saying "Cannot read property 'length' of undefined"

What am I missing here? Is the controller running before the function that defines the var chapter?

2

There are 2 best solutions below

1
Fan Cheung On

I guess it's because chapter is a local variable to your $scope.getData function. For example

function foo(num){
   var myNum=num
}
foo(3)
console.log(myNum) // your will get undefinied

do this instead

var myNum
function foo(num){
   myNum=num
}
foo(3)
console.log(myNum) // your will get 3
3
Madhankumar On

Actually the problem is from the ng-repeat u r sending the item (which is an array element, primitive type not an object) to the function getData(). That's why it returns cannot read property length undefined. I hope this helps you.

Var items = [ 'apple',  'mango'] ;
items.length //2
Items[0].length // error