简体   繁体   中英

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

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 ?

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

Actually the problem is from the ng-repeat ur 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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