javascript - 将 SweetAlert2 与 Angular 一起使用时如何保持范围?

标签 javascript angularjs sweetalert sweetalert2

当我尝试添加SweetAlert2时对于我的 Angular 删除按钮,它会阻止范围更新模型。可以同时使用它们吗?

Shown here in this Plunker (请确保先添加项目,然后才能在示例中删除)

使用 SweetAlert 的代码不起作用(当我确认时没有任何反应):

function fieldToolsController($scope, ParticipantFactory) {
  var model = this;
  model.participant = ParticipantFactory;
  model.participant.hasRoles = model.participant.roles.length > 0;

  model.deleteSelectedRole = function () {
    for (var i = 0; i < model.participant.roles.length; i++) {
      if (model.participant.roles[i] === model.participant.selected) {

        swal({
          title: 'Are you sure?',
          text: "You won't be able to revert this!",
          type: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, delete it!'
        }).then(function () {

          //=============================
          //LOSES SCOPE HERE OR SOMETHING
          //=============================
          model.participant.roles.splice(i, 1);
          model.participant.hasRoles = model.participant.roles.length > 0;
          if (model.participant.hasRoles) {
            model.participant.selected = model.participant.roles[0];
          }
          return;
          //=============================
          //=============================
          //=============================

        });

      }
    }
  };
}

下面是与普通 javascript 警报一起正常工作的相同函数:

And the plunker

function fieldToolsController($scope, ParticipantFactory) {
  var model = this;
  model.participant = ParticipantFactory;
  model.participant.hasRoles = model.participant.roles.length > 0;

  model.deleteSelectedRole = function () {
    for (var i = 0; i < model.participant.roles.length; i++) {
      if (model.participant.roles[i] === model.participant.selected) {

        var c = confirm("Are you sure?");
        if(c){
          model.participant.roles.splice(i, 1);
          model.participant.hasRoles = model.participant.roles.length > 0;
          if (model.participant.hasRoles) {
            model.participant.selected = model.participant.roles[0];
          }
          return;

        }

      }
    }
  };
}

最佳答案

由于该函数稍后会执行(这是一个 promise ),因此您可能需要提供 model 变量作为注入(inject)参数。

在您的 .then 函数中,尝试将 model 变量注入(inject)其中,如下所示:

.then(function(model) {
    console.log(model)
});

关于javascript - 将 SweetAlert2 与 Angular 一起使用时如何保持范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731734/

相关文章:

javascript - 如何使用 YUI Compressor 自动压缩 JavaScript 文件?

javascript - 无限滚动+ masonry 崩溃

javascript - 按下鼠标时展开谷歌地图圆圈

javascript - 地址栏中的 Angularjs 编码值

javascript - ng-repeat 不起作用,但可以在页面上获取 $scope.items 的项目

javascript - 在弹出窗口中隐藏网址栏

AngularJS - ng-水平重复 x 次,然后换行

javascript - Ajax 在这两种情况下都运行

javascript - 无法使用 SweeAlert (angular-sweetalert) 更新 AngularJs 中的 View 调用两次更新 View 。为什么?

jquery - 通过 SweetAlert 确认删除数据表中的行