Angular $scope 不会在 bootbox 回调中更新

Angular $scope won't update in bootbox callback

这是我关于 SO 的第一个问题。

当我在作用域上拼接一个数组元素时,在 bootbox.js.

的回调中完成时,该更改不会反映出来

作品:

$scope.deleteA = function() {
    if (confirm("Really delete Item 3?")) {
      $scope.itemsA.splice(2, 1);
    }
}

无效:

$scope.deleteB = function() {
    bootbox.confirm("Really delete Item 3?", function(answer) {
      if (answer === true) {
        $scope.itemsB.splice(2, 1);
      }
    });
}

我主要想了解原因。对我来说,这比花哨的解决方法重要得多。

I created a Plunker to show the effect

来自 angular 外部世界的 angular 范围变量发生的任何更改,都不会将 angular 摘要系统与 运行 摘要循环联系起来以更新绑定。
bootbox 回调中 angular 不知道有什么变化,这就是为什么不更新视图。
要解决此问题,您需要使用 $apply method, or $timeout service 手动启动摘要循环,例如

bootbox.confirm("Really delete Item 3?", function(answer) {
  if (answer === true) {
    $scope.$apply(function(){
        $scope.itemsB.splice(2, 1);
    });
  }
});

应用范围更改的安全方法是使用 $timeout 服务。

bootbox.confirm("Really delete Item 3?", function(answer) {
  if (answer === true) {
    $timeout($scope.itemsB.splice(2, 1));
  }
});

因此您无需担心 $digest 阶段,您的 $apply 将是一个高调用堆栈,请查看 AngularJS Wiki - Anti-Patterns 点 -2。

Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.