I checked similar Q&As but they didn\'t fix my issue.
I want to dynamically set the class of an input, consider the following Plunkr.
You can simply check if there is anything typed in the input like so:
<input type="text" ng-model="Person.Name" ng-class="{'mandatory': !Person.Name.length}" />
This way you get rid of your error. Because you were updating the Cnt
$scope variable in your function, the digest cycle was triggered over and over again. That caused the infinite loop (the error you were seeing).
By simply checking if Person.Name
has a length, you avoid declaring a new function and other unnecessary logic. It's simple and much cleaner.
Hope this helped.
Update using ngForms:
You can declare a directive for validating your input like so:
app.directive('validate', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ngModelCtrl) {
scope.$watch('Person.Name', function(newValue) {
ngModelCtrl.$setValidity('notEmpty', isEmpty(newValue))
});
}
}
});
function isEmpty(string) {
return !!string.length;
}
and use it on your input
<input type="text" validate ng-model="Person.Name"/>
and in your CSS you will have
input.ng-invalid {
border: 2px solid red;
}
Now you can delcare how many and complex validation functions and simply use the $setValiditity()
function to tell Angular if that input is valid or not. If one of your validation will turn false, then Angular will automatically turn your input red by adding the ng-invalid
class.