Requirement: Create a generic controller function in Angular JS that will cater to all the input types.
2 Answers
What you want then is to:
- add the
filledcss class when the form field has a value, and - remove the
filledcss class when the form field doesn't have a value - do both of the above using a reusable function in an angular controller.
You can achieve this using Angular's built-in ng-class directive:
HTML:
<input
id="renewccCVV"
type="number"
class="form-control"
ng-class="isFilled(RenewCard.cvv)"
ng-model="RenewCard.cvv"
maxlength="4" />
JS:
$scope.isFilled = function(value){
return (!!value) ? "filled" : "";
}
1 Comment
Add the below code to Angular js controller. 'filled' is the css class that I want to make use of. I am passing the $event from my ng-blur event in HTML input control.
$scope.addCssClass = function (event) {
if (event !== null && event.target !== null) {
if (event.target.value !== "") {
if (event.target.className.search('filled') < 0) {
var classes = event.target.className;
classes += ' filled';
event.target.className = classes;
}
}
else {
event.target.classList.remove('filled');
}
}
};
Here is the snippet of HTML code.
<input id="renewccCVV" type="number" class="form-control" ng-blur="addCssClass($event)" ng-model="RenewCard.cvv" maxlength="4" />
If my input control has value and css class 'filled' is not added to ng-class , then add the css class, if the input already has css class and value is not null, do not add the class. When the value from input control is removed, then remove the css class from the classList.