$compile(ele)(scope);
编译指令元素中的行,这将导致在无限循环中调用编译指令代码,这就是它给出的原因“RangeError: Maximum call stack size exceeded”
error.
理想情况下,您应该结合使用编译和链接功能。从编译功能中,您需要添加ng-class
attribute & 然后删除指令属性以避免指令元素无限期编译。然后使用指令链接函数的范围编译指令元素。
Code
myApp.directive('twinField', function($compile) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
fval: '='
},
compile: function(tElement, tAttrs) {
console.log(tElement)
tElement.removeAttr('twin-field');
return function(scope, ele, attr, ctrl) {
ele.attr("ng-class", "addForm.cpassword.$error.compareTo?'errorpswd':''");
ele.attr("test", "{{test}}':''");
var compileFn = $compile(ele);
ctrl.$validators.compareTo = function(val) {
//alert(scope.fval)
return scope.fval == val
}
scope.$watch('fval', function(newValue, oldValue, scope) {
ctrl.$validate()
});
compileFn(scope);
}
}
}
})
类似的答案 https://stackoverflow.com/questions/31061732/angularjs-custom-form-validation-directive-doesnt-work-in-my-modal/31062143#31062143
演示在这里 http://plnkr.co/edit/5DWS9ya8IZzqaLyykHhf?p=preview
但另一件事,我没有看到使用添加和删除类的代码有任何优势ng-class
指示。当您设置表单控件的有效性时,您隐式地添加和删除ng-valid-compare-to
(有效)和ng-invalid-compare-to
(无效)类。因此无需创建额外的开销即可ng-class
再次放置相同内容的逻辑。