简体   繁体   English

使用ng-init将数据从ng-repeat发送到另一个控制器

[英]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 我有一个运行ng-repeat的html文件,然后该ng-repeat中的每个项目都会生成一个模板,该模板也具有自己的控制器

On the html file I have something like: 在html文件上,我有类似以下内容:

<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: 控制器具有函数getData(item),看起来像这样:

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

$scope.myVec = chapter.myVec.length;

template.html looks like: template.html看起来像:

<div ng-controller = "Controller">

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

</div>

And then I get an error on the console saying "Cannot read property 'length' of undefined" 然后我在控制台上收到一个错误,提示“无法读取未定义的属性'length'”

What am I missing here? 我在这里想念什么? Is the controller running before the function that defines the var chapter ? 控制器是否在定义var chapter的功能之前运行?

I guess it's because chapter is a local variable to your $scope.getData function. 我猜这是因为Chapter是$ scope.getData函数的局部变量。 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(). 实际上,问题出在ng-repeat ur将项目(这是一个数组元素,原始类型不是对象)发送到函数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

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

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