在Angular js中,如何在没有提交按钮的情况下创建表单

时间:2014-02-18 13:11:02

标签: angularjs angularjs-directive

我尝试创建一个angular指令ng-smart-submit,其中没有提交按钮。当其中一个表单元素失去焦点时,表单会自动提交。

这是一个傻瓜:http://plnkr.co/edit/xP92p3zBwHsXWsOzVefl?p=preview

这是指令代码:

angular.module('plunker').directive("ngSmartSubmit", [
  function() {
    return {
      restrict: "A",
      require: "ngModel",
      scope: {
       form: "=ngSmartSubmit",
    data: "=ngSmartModel"
  },
  link: function(scope, element, attrs, ctrl) {
    var action;
    action = function(parentScope) {
      if (ctrl.$dirty) {
        scope.form.$setPristine();
        if (ctrl.$valid) {
          return parentScope.update(scope.data, function(succeed) {
            ctrl.$updated = succeed;
          });
        } else {
          return parentScope.$emit('ngSmartSubmit::controlInvalid');
        }
      }
    };
    ctrl.$updated = false;
    scope.$parent.$on('ngSmartSubmit::controlModified', function() {
      return scope.$apply(function() {
        ctrl.$updated = false;
      });
    });
    return element.bind("focus", function(evt) {
      return scope.$apply(function() {
        ctrl.$updated = false;
      });
    }).bind("blur", function(evt) {
      return scope.$apply(function() {
        return action(scope.$parent);
      });
    }).bind("keydown keypress", function(evt) {
      if (evt.which === ENTER_KEY) {
        scope.$apply(function() {
          return action(scope.$parent);
        });
        return event.preventDefault();
      } else {
        return scope.$parent.$emit('ngSmartSubmit::controlModified');
      }
    });
  }
    };
  }
]);

请建议,我如何改进ng-smart-submit指令。

提前致谢。

0 个答案:

没有答案