AngularJS中的确认模式

时间:2015-01-22 13:39:41

标签: javascript angularjs

我有一个管理订阅的应用程序。

<table>
  <thead>
    <tr>
      <th>Subscription Name</th>
      <th>Auto Renew</th>
    </tr>
  </thead>
  <tbody ng-controller="SubscriptionController as subCtrl>
    <tr ng-repeat="subscription in subCtrl.subscriptions">
      <td>
      {{ subscription.name }}
      </td>
      <td>
        <input type="checkbox" name="onoffswitch" class="autorenew onoffswitch-checkbox" id="switch-{{ subscription.id }}" value="1" ng-checked="subscription.auto_renew" switchtoggle="subCtrl.toggleAutoRenew({{subscription.id}})">
      </td>
    </tr>
   </tbody>
 </table>

该复选框有一个名为switchToggle的指令。我使用它来管理模型,因为我需要能够观察变化并要求确认模态。该指令只运行控制器的toggleAutoRenew函数

/**
 *
 */
app.directive('switchtoggle', function () {
  return {
    restrict: 'A',
    link: function(scope, element, attrs)
    {
      element.bind('change', function(){ 
        scope.$apply(attrs.switchtoggle);
      });
    }
  };
});

我无法弄清楚该怎么做是创建一个带有确认和取消按钮的模态。这样当有人点击复选框(看起来像开关)时,我可以确认他们是否真的想要打开或关闭。

请帮忙....

2 个答案:

答案 0 :(得分:1)

所以我也建议使用UI Bootstrap's Modal Dialog,但在你串起来之前阅读完整的答案:)

首先,这是一个demo of your EXACT scenario

现在让我介绍一下代码。

我对您的标记所做的唯一更改是删除自定义指令,转而使用简单的ng-click处理程序。

ng-click="subCtrl.toggleAutoRenew($event, subscription)

请注意我在那里传递的$event,这很重要,因为它允许我们调用.preventDefault(),这将阻止模型更新,并让我们有机会展示给用户的确认对话框。

toggle方法传入整个订阅对象,然后简单地取消进一步的事件处理。

toggleAutoRenew: function($event, subscription) {
      var _this = this;

      $event.preventDefault();
      $event.stopPropagation();

      _this.confirmAutoRenew(subscription)
        .then(function() {
          subscription.auto_renew = !subscription.auto_renew;
        });
    }

然后我们调用另一个负责显示返回promise的对话框的方法。

如果解决了承诺,那么我们切换auto_renew对象上的subscription标记,一切都按预期工作。

如果承诺被拒绝,那么我们什么都不做,订阅永远不会更新。对于用户来说,好像他们从未点击过该复选框一样。

您可以查看该示例,了解该方法如何利用UI Bootstrap和$modal服务来显示对话框并处理结果,但逻辑都在里面切换方法, 100%由控制器处理

答案 1 :(得分:-1)

在这里你可以看到如何打开模态: http://angular-ui.github.io/bootstrap/

顺便说一句,这是你的输入应该是这样的:

<input type="checkbox" class="autorenew onoffswitch-checkbox" ng-model="subscription.auto_renew" ng-change="subCtrl.toggleAutoRenew(subscription)">