您的位置:首页 > Web前端 > AngularJS

让Angularjs外面表单忽略对内嵌表单的校验

2015-01-30 22:05 323 查看
从stackoverflow中收到的解答,地址http://stackoverflow.com/questions/19333544/skip-nested-forms-validation-with-angularjs

自定义isolate-form directive作为内嵌的表单,能够绕过外面表单的验证。customed directives as follows:

angular.module('isolateForm',[]).directive('isolateForm', [function () {
return {
restrict: 'A',
require: '?form',
link: function (scope, elm, attrs, ctrl) {
if (!ctrl) {
return;
}

// Do a copy of the controller
var ctrlCopy = {};
angular.copy(ctrl, ctrlCopy);

// Get the parent of the form
var parent = elm.parent().controller('form');
// Remove parent link to the controller
parent.$removeControl(ctrl);

// Replace form controller with a "isolated form"
var isolatedFormCtrl = {
$setValidity: function (validationToken, isValid, control) {
ctrlCopy.$setValidity(validationToken, isValid, control);
parent.$setValidity(validationToken, true, ctrl);
},
$setDirty: function () {
elm.removeClass('ng-pristine').addClass('ng-dirty');
ctrl.$dirty = true;
ctrl.$pristine = false;
},
};
angular.extend(ctrl, isolatedFormCtrl);
}
};
}]);
To use it just call the directive "isolate-form" :
<form name="parent">
<input type="text" ng-model="outside"/>
<ng-form name="subform" isolate-form>
<input type="text" ng-model="inside"/>
</ng-form>
</form>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: