javascript - 使用 ng-init 将数据从 ng-repeat 发送到另一个 Controller

标签 javascript angularjs angularjs-ng-repeat angularjs-ng-init

我有一个运行 ng-repeat 的 html 文件,然后该 ng-repeat 中的每个项目都会生成一个模板,该模板也有自己的 Controller

在 html 文件中我有类似的内容:

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

然后这个模板有它自己的 Controller 。

Controller 具有 getData(item) 函数,看起来像这样:

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

$scope.myVec = chapter.myVec.length;

template.html 看起来像:

<div ng-controller = "Controller">

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

</div>

然后我在控制台上收到错误消息“无法读取未定义的属性‘长度’”

我在这里缺少什么? Controller 是否在定义 var 章节 的函数之前运行?

最佳答案

我猜这是因为 Chapter 是 $scope.getData 函数的局部变量。例如

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

改为这样做

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

关于javascript - 使用 ng-init 将数据从 ng-repeat 发送到另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391648/

相关文章:

javascript - 当单选按钮选择更改时清除复选框

javascript - 在各种浏览器中测试 jQuery 插件

angularjs - 从服务中刷新特定 Controller $scope

java - 无法从 JSON 字符串实例化类型的值;没有单字符串构造函数/工厂方法

javascript - 使用 Angular ng-repeat 在数组中显示数组对象

javascript - 使用 httpOnly cookie 进行设备注册

javascript - 当用户更具体地填写输入时更新表选项

javascript - 如何在一个 Node 包中创建 AngularJs 指令,然后将其包含在应用程序的另一个 Node 包中?

javascript - ng-repeat 指令中的 Angular 选择 : how can I access the children scopes?

javascript - Ng-repeat 没有在 Flask 应用程序中显示我的项目。