Consider a scenario where we have a custom validator with an input as the attribute's value.
app.directive('inputRequired', function() {
return {
require: 'ngModel',
scope: {
inputRequired: '='
},
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.inputRequired = function(modelValue) {
return !(scope.inputRequired && ctrl.$isEmpty(modelValue));
};
}
};
});
In our scope, we define a variable and a function to toggle the variable's value:
$scope.isRequired = false;
$scope.toggle = function() {
$scope.isRequired = !$scope.isRequired;
};
Next, we create a form where this custom validator will be used. We also include a button that triggers the toggle function.
<form>
<input type="text" ng-model="someModel" input-required="isRequired"/>
<button ng-click="toggle()">toggle</button>
</form>
How does it work? Initially, when the form loads and the scope is initialized, the value of isRequired
is set to false
, making the input field not required. When we click the toggle button, the value of isRequired
changes to true
. However, validation is not triggered even though a variable on the validator's scope was updated.
It's worth mentioning that this example serves only as a demonstration. While the ng-required
directive can achieve similar functionality, we need a more general solution for cases where a validator depends on an input, and the field must be revalidated immediately if that input changes.