【问题标题】:AngularJS : variable of ng-repeat loop not updating $scope fast enoughAngularJS:ng-repeat循环的变量没有足够快地更新$scope
【发布时间】:2014-02-16 03:00:59
【问题描述】:

我在 $scope 中有一个项目树,我想在其上使用 ng-repeat 进行迭代,并根据节点类型包含不同的模板。这棵树有点像

$scope.item = {
  ID: 1,
  children: {
    1: {
      ID: 11,
      },
    2: {
      ID: 12,
    }
  },
};

问题是当我做类似的事情时

<div ng-repeat="item in item.children">
  item.ID : {{item.ID}}
  <div ng-include="showVars(item.ID)"></div>
</div>

showVars 函数的参数是在父范围内评估的 item.ID 值,而不是由 ng-repeat 创建的子范围。当使用{{item.ID}} 显示时,该值是正确的。

this Fiddle 中的示例。

我的理解是调用函数时子作用域中的值还没有更新,对吗?这是 AngularJS 的正常行为还是错误?

编辑:

为了更明确,我希望在小提琴中

calling getTemplate with $scope.item.ID = 12 and itemID = 12

而不是

calling getTemplate with $scope.item.ID = 1  and itemID = 12

因为 ng-repeat 应该为 $scope.item 分配变量。

谢谢,

【问题讨论】:

  • 我不明白问题出在哪里。所有日志都显示该方法收到了正确的项目 ID:“and itemID = 12”。并且包含的​​模板还显示子 ID:“My Template with item.ID = 12”。
  • 对不起,我应该更明确一点:问题是,正如您在日志中看到的那样,当评估 ng-include 时,$scope.item 仍然与父作用域中的相同,而我希望它是由 ng-repeat 创建的子范围的 $scope.item。为了更明确,我希望calling getTemplate with $scope.item.ID = 12 and itemID = 12 而不是calling getTemplate with $scope.item.ID = 1 and itemID = 12

标签: angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

这是预期的行为。

当您创建控制器的showVars 函数时,您将关闭$scope,这是父控制器的范围。因此,当您引用 $scope 时,您将获得注入控制器的作用域。

换句话说,$scope 不会根据函数的执行而改变。这就是为什么要将项目作为参数传递给函数的原因。

如果你想访问函数中的子作用域,你可以使用this

this.item.ID

这是一个有效的JS Fiddle

【讨论】:

  • 非常感谢,这对我帮助很大!我现在全面了解,尤其是在this answerthis doc 的帮助下。
  • 谢谢,@ElieRoux。如果您喜欢我的回答,请将其标记为正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 2011-07-31
  • 2015-10-28
  • 1970-01-01
相关资源
最近更新 更多