当我点击Angularjs中的模态弹出关闭按钮(x)时重置表单

时间:2017-06-16 06:47:35

标签: angularjs

我在模态弹出窗口中有表单。我正在使用指令打开模态弹出窗口

mymodule.directive('modalDialogSite', function() {
  return {
    restrict: 'E',
    scope: {
      show: '='
    },
    replace: true, // Replace with the template below
    transclude: true, // we want to insert custom content inside the directive
    link: function(scope, element, attrs) {
      scope.dialogStyle = {};
      if (attrs.width)
        scope.dialogStyle.width = attrs.width;
      if (attrs.height)
        scope.dialogStyle.height = attrs.height;
        if (attrs.overflow)
        scope.dialogStyle.overflow = attrs.overflow;
      scope.hideModal = function() {
        scope.show = false;
      };
    },
    template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'><i class='fa fa-times-circle'></i></div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"// See below
  };
});

如果我在模态弹出窗口中单击取消按钮我使用$ setpristine重置表单但如果我点击关闭按钮(x)时有任何验证错误它调用hideModal()函数,因此模态得到关闭,但如果我重新打开模态弹出模态弹出窗口中仍然存在验证错误。如何重置该表单。这是我的工作Plnkr https://plnkr.co/edit/embFJFmautH3uRbHOWU7?p=preview

1 个答案:

答案 0 :(得分:0)

我想你在这里错过了几件事。我为此创建了一个plunkr,它非常自我解释。您可以转到它并观察它正是您所需要的。模态内部的表单在打开时会进入初始状态,并且代码在此工作的plunkr中组织得很好。打开模态时,表单也会重置。

app.directive('modalDialogAdd', function() {

    return {
    restrict: 'E',
    scope: {
      show: '='
    },
    replace: true,
    transclude: true,
    link: function(scope, element, attrs) {
        scope.dialogStyle = {};
        scope.text ={
        first_name : '',
        last_name: ''
      };

        if (attrs.width)
            scope.dialogStyle.width = attrs.width;
        if (attrs.height)
            scope.dialogStyle.height = attrs.height;
        if (attrs.overflow)
            scope.dialogStyle.overflow = attrs.overflow;
        scope.hideModal = function() {
              scope.show = false;
        };
           scope.$watch('show', function (newVal, oldVal) {
              if(newVal){
                  var childFormController = element.find('form').eq(0).controller('form');
                  childFormController.$setPristine();
                  childFormController.$setUntouched();
              }
          });

    },
        template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'><i class='fa fa-times-circle'></i></div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
    };
});

这是一个有效的plunkr PLUNKR