我有一个单页的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
表达式?
答案 0 :(得分:0)
当你没有使用$http
发出服务器请求时,这种情况经常发生,因为$ http会在请求完成并执行回调后负责执行摘要周期。
如果您使用的是$ajax
并且由于某种原因您无法使用$http
,那么无论您在ajax回调中设置值,您都必须将该代码包装在$scope.$apply
方法中内部调用$scope.$digest
方法来更新任何绑定或观察者。
E.g
if(!$scope.$$phase) {
$scope.$apply(function () {
$scope.purchase = //Set the purchase object/value
});
}