【问题标题】:How do you keep the scope when using SweetAlert2 with Angular?将 SweetAlert2 与 Angular 一起使用时如何保持范围?
【发布时间】:2016-11-22 00:10:14
【问题描述】:

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

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;

        }

      }
    }
  };
}

【问题讨论】:

    标签: javascript angularjs sweetalert sweetalert2


    【解决方案1】:

    由于函数稍后执行(这是一个承诺),您可能需要提供model 变量作为注入参数。

    在您的.then 函数中,尝试像这样将model 变量注入其中:

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

    【讨论】:

    • 是的 - 我确实试过了。我也希望它会那么简单。给出此错误:app.js:26 Uncaught (in promise) TypeError: Cannot read property 'roles' of undefined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多