I need to access input elements of a forms collection to do some custom validation. This worked just fine like this:
scope.myForm.value3.$setValidity('complex', valid);
until I converted value3 into a directive which in turn contains the input element named value3. Now I have no access to the underlying input element of the directive any more.
The important code goes as follows (working plunker here):
<form name="myForm" two-values>
<input id="value1" name="value1" ng-model="f.v1"/>
<input id="value2" name="value2" ng-model="f.v2"/>
<szp-input id="value3" value="f.v3"></szp-input>
</form>
app.directive('twoValues', function ($parse) {
function isValid(scope, value1, value2) {
var valid = true;
if (value1 == 0 && value2 == 0) {
valid = false;
} else if (value1 != 0 && value2 != 0) {
valid = false;
}
console.log(scope.myForm);
// note that I can access value1 and value2, but not value3
// which is encapsulated in a directive
scope.myForm.value1.$setValidity('complex', valid);
scope.myForm.value2.$setValidity('complex', valid);
// this throws and error saying that value3 is undefined
scope.myForm.value3.$setValidity('complex', false);
}
return {
restrict: 'A',
replace: true,
link: function (scope, elem, attr, ctrl) {
scope.$watch('f.v1', function () {
isValid(scope, scope.f.v1, scope.f.v2);
});
scope.$watch('f.v2', function () {
isValid(scope, scope.f.v1, scope.f.v2);
});
}
};
});