【问题标题】:Angular ngBind with function / complex expression带有函数/复杂表达式的 Angular ngBind
【发布时间】:2015-06-04 20:56:38
【问题描述】:

我有一个单页 Angular 购买表单,其中包含多种选项和一个显示在表单各个部分的运行估计总数。计算估计的总内联相当复杂且难以测试:

<span ng-bind="purchase.itemTotal + selectedInsurance() + selectedShipping()">?</span>

我试图通过重构作用域上的一个函数来干掉我的观点,并将ng-bind指定为这个函数:

$scope.estimatedTotal = function() {
  if ($scope.purchase)
    return $scope.purchase.itemTotal + $scope.selectedInsurance() + $scope.selectedShipping();
}

if 语句是必要的,因为它有时会在通过 Ajax 填充模型 $scope.purchase 之前进行评估。问题是该函数最初在 Ajax GET 完成之前返回 undefined,但随后 ngBind 不会再次重新评估它。

我可以告诉ngBind 留意其他模型值吗?是否有另一种推荐的方法来重构复杂的 ngBind 表达式以很好地进行脏检查?

【问题讨论】:

  • but then ngBind does not re-evaluate it again --> 检查控制台中的任何错误。你在使用 $http 进行 ajax 对吗?
  • 我正在使用 angular rails resource 与 Rails 应用程序集成,这在引擎盖下使用了 $http。此外,Ajax 只是问题的一部分,因为它也不会在用户更新时重新评估,例如,$scope.purchase.itemTotal

标签: javascript ajax angularjs data-binding ng-bind


【解决方案1】:

这主要发生在您不使用$http 发出服务器请求时,因为一旦请求完成并执行回调,$http 会负责执行摘要循环。

如果您正在使用$ajax,并且由于某种原因您不能使用$http,那么无论您在ajax 回调中设置值的任何位置,都必须将该代码包装在$scope.$apply 方法中,该方法将在内部调用$scope.$digest 方法更新任何绑定或观察者。

例如

if(!$scope.$$phase) {
  $scope.$apply(function () {
    $scope.purchase = //Set the purchase object/value
  });
}

【讨论】:

  • 我正在使用 angular rails resource 与 Rails 应用程序集成,这在引擎盖下使用了 $http。当我尝试在$scope.$apply 中包装分配时,我收到一个错误“$digest 已经在进行中”。此外,Ajax 只是问题的一部分,因为它也不会在用户更新时重新评估,例如,$scope.purchase.itemTotal
  • 对不起,这个项目被搁置了,所以我花了一段时间来测试。当我以这种方式包装分配时,事实证明没有分配任何内容,因为$scope.$$phase 始终是"$digest"
  • 无论如何,我不只是询问何时通过 AJAX 更新值;我还在询问它何时通过ng-model 的用户输入更新,它也不会更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多