Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SweetAlert2, .then() - not updating DOM immediately

THE PROBLEM:
I want to redirect a user to another page after clicking OK on the sweet alert, but the user is not redirected until I open up another sweet alert for some reason.
You can breakpoint over the code, but nothing happens on the page.

Simple example of the problem: http://jsfiddle.net/ADukg/14306/

NOTE: including a 0 second timeout "solves the problem"

To Reproduce:
1) Note the text after the arrow.. $scope.name = "original", and you can see it's displayed on the page.
2) Click the "click first" button. This runs the function $scope.changeMe(), which updates $scope.name to "delayed......."
3) By now, the text above the buttons should have been changed. But it's not until you open up another sweet alert does the text actually change
4) Click the "then here" or "click first" button so another sweet alert pops up, and the DOM will finally change.

I'm pretty sure this is somehow related to AngularJS, and 1.4.3 has to be used.

Any ideas?

HTML:

<div ng-controller="MyCtrl">
  <div>
    <button ng-click="changeMe()">click first</button>
    <button ng-click="decoy()">then here</button>
  </div>
  <div>
    <button ng-click="reset()">reset text</button>
  <div>
</div>

JS:

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl", function($scope, $timeout) {
    $scope.name = 'original';
    $scope.copy = angular.copy($scope.name);

    $scope.changeMe = function() {
      swal("Text should change now")
      // runs on hitting "OK"
      .then(function() {
                  // UNCOMMENT THIS and re-run the fiddle to show expected behavior
          // $timeout(function() { $scope.displayErrorMsg = false; }, 0);
          $scope.name = 'delayed.......'
      })
    }

    $scope.decoy = function() {
        swal("Look at the text now");
    }

    $scope.reset = function() {
        $scope.name = $scope.copy;
    }
})
like image 303
Sergnio Avatar asked Sep 21 '17 19:09

Sergnio


1 Answers

I see some problems in your fiddle

1)swal is not an angular library. So it won't work along with angular digest cycle, that is why it works only after $timeout is called. this tutorial explains why and how to fix it.

2)I see you have added ng sweet alert as a dependency but that is called before angular, so it doesn't not register in your fiddle and there is a console error.

3)If you were trying to use ng-sweet-alert it doesn't use this syntax. You need to include it in depedency first

var myApp = angular.module('myApp',['oitozero.ngSweetAlert']);

And it doesn't return a promise and it needs to be called differently.

SweetAlert.swal("Here's a message");
like image 159
Shyam Babu Avatar answered Oct 16 '22 21:10

Shyam Babu