为了减少html验证的样板代码,我正在编写两个指令:一个用于模板化,另一个用于验证…两个指令都按预期工作,而
angularjs验证类确实附加到无效的输入标签,只有我面临验证的问题作为模板指令一部分的消息未显示.
PLUNKER LINK
问题似乎与编译子元素的方式有关:
element.replaceWith($compile(template)(scope));
这应该是用父元素编译,但如何做到这一点?
解决方法
是的,你是对的,问题确实存在
element.replaceWith($compile(template)(scope));
你在编译它后把元素放在dom上,你正在反向,因此ngmodel没有改变连接本身到父窗体.
你在做什么是:
1. create & compile element 2. place it in dom
因为元素在进入dom之前已经被编译了..它永远不会知道它的父形式,因此不会将自己链接到父元素.
步骤的顺序应该是:
1. create an element,2. place it in dom 3. compile it. // now it will have a chance to hook up to the parent
所以你应该做的是:
var el =angular.element(template); element.replaceWith(el); $compile(el)(scope);
检查plunker链接:http://plnkr.co/edit/hwyuuzeAnu5oBQqmmpR3?p=preview