Angular 1.x:为什么2路绑定不起作用?

时间:2016-09-09 19:07:29

标签: angularjs angularjs-scope

我没有使用一些复杂的指令,而是简单的乘法和角度的双向绑定似乎失败了。当我说失败时,它在我乘以时不会更新视图。但是,当我点击某个UI元素或以某种方式更改视图时,例如单击单选按钮。神奇地出现了这个价值。经过一番调查后,我发现当我繁殖时没有调用应用程序。所以我添加了$ scope。$ apply(function(){})。这似乎解决了它。但正如我在一些帖子中读到的那样。你永远不应该尝试明确地调用$ apply。这引出了一个问题。到底发生了什么? console.log()显示已更改的值,但该值未在视图中应用。我也不是直接操纵范围。对于前。

 $scope.calculateOutstationCharges = function() {
        if ($scope.customer.calculatedDistance !== 0) {
            console.log($scope.customer.kmlimit * $scope.carPricing.perKmCharge * $scope.customer.days);
            if (($scope.customer.calculatedDistance * 2) < $scope.carPricing.kmlimit * $scope.customer.days) {
                $scope.customer.totalprice_outstation = $scope.carPricing.kmlimit * $scope.carPricing.perKmCharge * $scope.customer.days + $scope.customer.driverCharge;
//console.log($scope.customer.totalprice_outstation). This value is not updated in the view
            } else {
                $scope.customer.totalprice_outstation = ($scope.customer.calculatedDistance * 2 * $scope.carPricing.perKmCharge)+  $scope.customer.driverCharge;
                //console.log($scope.customer.totalprice_outstation); nor is this one
            }
            $scope.customer.totalprice_outstation += $scope.customer.extra_outstation;
        }
         $scope.customer.driverCharge = $scope.carPricing.driverCost;
$scope.$digest(); //this does it but with $apply in progess error.
    };

值将在下一个摘要周期中更新,而不是在创建值的周期中更新。 如果你们中的任何一个人遇到过类似的问题,你们会怎样解决它? 感谢

2 个答案:

答案 0 :(得分:1)

$ scope.CalculateOutstationCharges是从angular的上下文之外调用的(我正确吗?)。

Angular并不知道$ scope变量已更改。你需要明确告诉角度这个。为此,您必须致电

$timeout(function(){$scope.$apply();})

哪个会等待当前的摘要周期完成。然后它将在DOM上应用更改的$ scope变量。

答案 1 :(得分:0)

角度上下文之外的事件应该告知变化的角度,正如您提到的那样,不建议使用$ apply。

Check $applyAsync([exp]);

相关问题