我的情况类似于this question。我唯一的转折是我在页面完成初始渲染/绑定后的某个时刻异步(通过webservice调用)接收我的“动态”信息。所以,我的指令流程是这样的:
**更新:完成repro:http://plnkr.co/edit/TIVbhGFMAQpUaMxKp9Dc?p=info
Markup: <input dynValidate />
Directive:
app.directive('dynValidate',function($compile,$parse) {
restrict: 'A', require: 'ngModel', replace: false, terminal: true,
link: function (scope, elem, attr, ctrl) {
var validatorKey = elem.attr('ng-model') + 'Validation';
var installValidators = function () {
// ...add some ng-validation attributes
// (omitted for brevity, but does something like elem.attr('ng-minlength','5')
// based on metadata in the bound model
elem.removeAttr('dynValidate'); // Remove my own directive
$compile(elem)(scope); // recompile to incorporate new ng directives
}
};
// watch for the validation metadata to arrive asynchronously
scope.$watch(validatorKey, function() {
installValidators(attr, ctrl);
});
}
});
这种工作方式:我的指令属性被一些角度验证指令取代,验证在此元素的级别上正常运行。问题是异步重新编译似乎导致父ng-form失去对元素的跟踪。具体来说,当输入更改时,form.fieldName。$ isDirty将永远不会设置为true。这是有道理的,因为我基本上删除了原始元素并用不同的元素替换它,但我想知道是否有任何机制允许我告诉父表单这已发生,并且它应该挂钩它表单级别的$ error / $ dirty机制。
谢谢!