我尝试创建一个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
指令。
提前致谢。