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

来源:互联网 发布:赫连勃勃大王知乎 编辑:程序博客网 时间:2024/05/18 04:46

从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>


0 0
原创粉丝点击