Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $scope won't update in bootbox callback

This is my first question on SO.

When I splice an element of an array on the scope, that change is not reflected, when done in a callback of bootbox.js.

Works:

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

Does not work:

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

I'm mainly interested in understanding the why. This is much more important to me than having a fancy workaround.

I created a Plunker to show the effect

like image 887
Danny Soul Avatar asked Mar 19 '16 10:03

Danny Soul


1 Answers

Any change happens with angular scope variable from ouside world of angular, doesn't intimate angular digest system to run digest cycle for updating binding.
In bootbox callback angular not know that something change, that's why not update view.
For solving this issue, you need to kick off digest cycle manually by using $apply method, or $timeout service, like this

bootbox.confirm("Really delete Item 3?", function(answer) {
  if (answer === true) {
    $scope.$apply(function(){
        $scope.itemsB.splice(2, 1);
    });
  }
});
like image 91
Grundy Avatar answered Nov 11 '22 12:11

Grundy