如何在更改输入约束后更新AngularJS中的表单控制器
我最近一直致力于动态更改表单上输入字段的约束.目的是制作一个后端驱动的表单,而所有字段及其约束都由服务器发送给我们.虽然我设法通过创建一个简单的指令来获得要添加/删除的约束,但似乎表单控制器没有获取这些更改,因此表单始终是$valid.看看
this jsfiddle,这是指令:
myApp.directive('uiConstraints',[function(){ function applyConstraints(element,newVal,oldVal){ //remove old constraints if(oldVal !== undefined && oldVal !== null){ for (var i = 0; i < oldVal.length; i++) { element.removeAttr(oldVal[i].key); } } //apply new constraints if(newVal !== undefined && newVal !== null){ for (var i = 0; i < newVal.length; i++) { var constraint = newVal[i]; element.attr(constraint.key,constraint.value); } } } function link(scope,element,attrs){ scope.$watch(attrs.uiConstraints,function(newVal,oldVal){ applyConstraints(element,oldVal); }); } return { restrict : 'A',link : link }; }]); 所需的行为是如此在official angularjs plunker上工作.但是,似乎在指令填充输入字段的约束之前创建FormController,并且更新这些约束不会更新FormController中的相应值. any1是否知道我是否可以强制FormController获取指令所产生约束的更改?如果是这样,怎么样?我不知道从哪里开始……谢谢. – 编辑 – >转到描述的jsfiddle
– 编辑 –
解决方法
看看这个
PLUNK
.directive('uiConstraints',["$compile",function($compile) { function applyConstraints(element,oldVal) { //apply new constraints if (newVal !== undefined && newVal !== null) { for (var i = 0; i < newVal.length; i++) { var constraint = newVal[i]; element.attr(constraint.key,constraint.value); } } } return { restrict: 'A',terminal: true,priority: 1000,require: "^form",link: function(scope,attrs,formController) { var templateElement; var previousTemplate; templateElement = element.clone(); //get the template element and store it templateElement.removeAttr("ui-constraints");// remove the directive so that the next compile does not run this directive again previousTemplate = element; scope.$watch(attrs.uiConstraints,oldVal) { var clonedTemplate = templateElement.clone(); applyConstraints(clonedTemplate,newVal); clonedTemplate.insertBefore(previousTemplate); var control = formController[previousTemplate.attr("name")]; if (control){ formController.$removeControl(control); } if (previousTemplate) { previousTemplate.remove(); } $compile(clonedTemplate)(scope); previousTemplate = clonedTemplate; }); } }; }]); 这里的想法是设置terminal:true和priority:1000让我们的指令首先编译并跳过同一元素上的所有其他指令以获取模板元素.如果您需要了解更多信息,请查看我的答案:Add directives from directive in AngularJS. 获取模板元素后,我删除了ui-constraints指令,以避免一次又一次地编译该指令,这会在每次切换约束时向摘要周期添加$watch. 每当约束发生变化时,我都会使用此模板元素构建一个包含所有约束的新元素,而不使用ui-constraints指令并对其进行编译.然后我从表单控制器中删除DOM及其控制器中的前一个元素,以避免泄漏和由表单控制器中存在的前一个元素的控制器引起的问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |