2017-09-21 60 views
8

问题:
我想点击甜蜜警报OK后,用户到另一个页面重定向,但用户不重定向,直到我打开了另一个甜蜜由于某种原因警觉。
您可以通过代码断点,但页面上没有任何反应。SweetAlert2,。那么() - 不更新DOM立即

问题的简单的例子:http://jsfiddle.net/ADukg/14306/

注意:包括0秒超时 “解决问题”

重现:
1)注意箭头.. $范围后的文字.name =“original”,你可以看到它显示在页面上。
2)点击“点击第一个”按钮。这将运行函数$ scope.changeMe(),它将$ scope.name更新为“delayed .......”
3)现在,按钮上方的文本应该已经更改。但直到你打开另一个甜蜜的警报文本实际上改变
4)点击“然后在这里”或“点击第一个”按钮,所以另一个甜蜜的警报弹出,DOM最终会改变。

我敢肯定,这与AngularJS有关,必须使用1.4.3。

任何想法?

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; 
    } 
}) 
+3

除非SweetAlert库是为Angular设计的,否则它将在Angular上下文外运行。必须调用Angular的摘要循环才能使更改生效。 'ng-click'应用摘要循环,这就是您在第二次点击后看到更改的原因。 '$ timeout'也调用摘要循环。看看你的例子'$ scope。$ apply()'added:http://jsfiddle.net/ADukg/14313/ –

+0

[ngSweetAlert](https://github.com/oitozero/ngSweetAlert)是要走的路你希望与angular进行适当的整合,否则你必须使用'$ scope。$ apply()'作为@AlexK上面提到的手动通知这种模型更改的角度。 –

+0

@AlexK完全解决了我的问题。我创建了一个Angular包装工厂,每一次我们都会使用甜蜜的警报。谢谢你的帮助!感谢您的确认Matthew Cawley! – Sergnio

回答

1

我看到你摆弄一些问题

1)SwaI位不是一个角库。所以它不会与角度摘要循环一起工作,这就是为什么它只在$ timeout被调用后才起作用。 this教程解释了为什么以及如何解决它。

2)我看到您已添加ng sweet alert作为依赖项,但在角度之前调用,所以它不会在您的小提琴中注册并且存在控制台错误。 3)如果你尝试使用ng-sweet-alert,它不会使用这种语法。您需要首先将其包含在依赖项中

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

而且它不返回承诺,它需要以不同的方式调用。

SweetAlert.swal("Here's a message");